题目
题目来源 : LeetCode
后序遍历二叉树,非递归实现
实现
//先实现栈
int* _postorderTraversal(struct TreeNode* root, int* a){
Stack s;
StackInit(&s);
int index = 0;
struct TreeNode* right = NULL;
struct TreeNode* cur;
if(root){
StackPush(&s, root);
root = root->left;
}
while(StackEmpty(&s) == 1 || root){
//访问左子树
while(root){
StackPush(&s, root);
root = root->left;
}
//右子树为空 或者 已经遍历 则访问根节点
cur = StackTop(&s);
if(cur->right == NULL || right == cur->right){
a[index++] = cur->val;
right = cur;
StackPop(&s);
}
//访问右子树
else{
root = cur->right;
}
}
return a;
}
//获取二叉树的节点个数
int Size(struct TreeNode* root){
if(!root){
return 0;
}
return Size(root->left) + Size(root->right) + 1;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize){
*returnSize = Size(root);
int* a = (int*)malloc(sizeof(int) * (*returnSize));
if(!root){
return a;
}
a = _postorderTraversal(root, a);
return a;
}