Problem
[链接登录后可见]
思路
解题方法
- 一直向左边走
- 到达左边尽头后弹出并打印,然后向右边走一个。
- 继续一直向左边走。
- 到达左边尽头后弹出并打印,然后向右边走一个。
- 结束条件是p和栈S都为空。
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
typedef struct stackNode {
struct TreeNode *data;
struct stackNode *next;
} stackNode;
typedef stackNode* Stack;
void Push(Stack* S, struct TreeNode *BTNode) {
if (*S) {
stackNode *p = (stackNode*)malloc(sizeof(stackNode));
p->data = BTNode;
p->next = *S;
*S = p;
} else {
stackNode *p = (stackNode*)malloc(sizeof(stackNode));
p->data = BTNode;
p->next = NULL;
*S = p;
}
}
struct TreeNode *Pop(Stack *S) {
struct TreeNode *p = (*S)->data;
stackNode *sp = *S;
(*S) = (*S)->next;
free(sp);
return p;
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
Stack S = NULL;
struct TreeNode *p = root;
int *a = (int*)malloc(sizeof(int)*100), *q = a;
while(p || S) {
if(p) {
Push(&S, p);
p = p->left;
} else {
p = Pop(&S);
*(q++) = p->val;
p = p->right;
}
}
*returnSize = q - a;
return a;
}