题目:
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
示例 1:
输入:root = [1,null,2,3]
输出:[3,2,1]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
提示:
- 树中节点的数目在范围 [0, 100] 内
- -100 <= Node.val <= 100
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/binary-tree-postorder-traversal
题解:
方法一:递归
后序遍历,按照访问左子树–右子树–根节点的顺序遍历二叉树,在访问左子树和右子树时按照同样的方式进行遍历,直到整棵树都被遍历,这就是递归的方法。
void postorder(struct TreeNode* root,int* result,int* returnSize){
if(root==NULL) return false;
postorder(root->left,result,returnSize);
postorder(root->right,result,returnSize);
result[(*returnSize)++]=root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize){
int* result=malloc(sizeof(int)*2000);
*returnSize=0;
postorder(root,result,returnSize);
return result;
}
执行结果:
方法二:迭代
用迭代的方式来实现方法一的递归,用栈来实现,实质上和递归是一样的,只不过递归的时候是隐式地维护了一个栈。
后序遍历与中序遍历的不同在于:
中序遍历中,从栈中弹出的节点,其左子树访问完了,可以直接访问该节点,然后访问右子树。
后序遍历中,从栈中弹出的节点,只知道它的左子树访问完了,但是无法确定右子树是否访问过。
所以在后序遍历中,要用一个prev来记录历史访问记录。
int* postorderTraversal(struct TreeNode* root, int* returnSize){
int* result=malloc(sizeof(int)*2000);
*returnSize=0;
struct TreeNode* stack[2000];
int top=0;
struct TreeNode* prev=NULL;
while(root!=NULL||top>0){
while(root!=NULL){
stack[top++]=root;
root=root->left;
}
root=stack[--top];
if(root->right==NULL||root->right==prev){
result[(*returnSize)++]=root->val;
prev=root;
root=NULL;
}
else{
stack[top++]=root;
root=root->right;
}
}
return result;
}
执行结果:
方法三:Morris 遍历
(来源:力扣官方题解)
void addPath(int *vec, int *vecSize, struct TreeNode *node) {
int count = 0;
while (node != NULL) {
++count;
vec[(*vecSize)++] = node->val;
node = node->right;
}
for (int i = (*vecSize) - count, j = (*vecSize) - 1; i < j; ++i, --j) {
int t = vec[i];
vec[i] = vec[j];
vec[j] = t;
}
}
int *postorderTraversal(struct TreeNode *root, int *returnSize) {
int *result = malloc(sizeof(int) * 2000);
*returnSize = 0;
if (root == NULL) return NULL;
struct TreeNode *p1 = root, *p2 = NULL;
while (p1 != NULL) {
p2 = p1->left;
if (p2 != NULL) {
while (p2->right != NULL && p2->right != p1) {
p2 = p2->right;
}
if (p2->right == NULL) {
p2->right = p1;
p1 = p1->left;
continue;
} else {
p2->right = NULL;
addPath(result, returnSize, p1->left);
}
}
p1 = p1->right;
}
addPath(result, returnSize, root);
return result;
}
执行结果: