1.题目:
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
2.代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
typedef struct TreeNode* Tree;
typedef struct{
Tree* array;
int top;
}Stack;
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
*returnSize=0;
int *r=malloc(1000*sizeof(int));
Stack* s=(Stack *)malloc(sizeof(Stack));
s->array=(Tree *)malloc(1000*sizeof(Tree));
s->top=0;
Tree t=NULL; //最近访问节点
while(root||s->top){
if(root){
s->array[s->top++]=root; //push()
root=root->left; //->left
}
else{
root=s->array[s->top-1];
if(root->right&&root->right!=t){
root=root->right;
//s->array[s->top++]=root; //push()
//root=root->left;
}
else{
root=s->array[--s->top]; //pop()
r[(*returnSize)++]=root->val; //visit()
t=root;
root=NULL;
}
}
}
return r;
}
3.知识点:
二叉树后序遍历,标记最近访问节点。