题目:
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
示例 1:
输入:root = [1,null,2,3]
输出:[3,2,1]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
来源:力扣(LeetCode)
链接:力扣
题解
C:
int* postorderTraversal(struct TreeNode* root, int* returnSize){
*returnSize = 0;
int *res = (int *)malloc(sizeof(int) * 501);
if(!root){
return res;
}
struct TreeNode *stk[501];
int top = -1;
struct TreeNode *prev = NULL;
while(root || top >= 0){
while(root){
stk[++top] = root;
root = root->left;
}
root = stk[top--];
if (!root->right|| root->right == prev) {
res[(*returnSize)++] = root->val;
prev = root;
root = NULL;
} else {
stk[++top] = root;
root = root->right;
}
}
return res;
}