【LeetCode-树】二叉树的后序遍历
题目描述
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
题目链接: https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
思路1
使用递归。代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
if(root==nullptr) return {};
vector<int> ans;
postOrder(root, ans);
return ans;
}
void postOrder(TreeNode* root, vector<int>& ans){
if(root==nullptr) return;
postOrder(root->left, ans);
postOrder(root->right, ans);
ans.push_back(root->val);
}
};
- 时间复杂度:O(n)
- 空间复杂度:O(h)
思路2
使用迭代。类似于中序遍历的颜色标记法。代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
if(root==nullptr) return {};
vector<int> ans;
stack<TreeNode*> nodeStack;
stack<int> visit;
nodeStack.push(root); visit.push(0);
while(!nodeStack.empty()){
TreeNode* curNode = nodeStack.top(); nodeStack.pop();
int hasVisit = visit.top(); visit.pop();
if(hasVisit==0){
nodeStack.push(curNode); visit.push(1);
if(curNode->right!=nullptr){
nodeStack.push(curNode->right); visit.push(0);
}
if(curNode->left!=nullptr){
nodeStack.push(curNode->left); visit.push(0);
}
}else{
ans.push_back(curNode->val);
}
}
return ans;
}
};
还有一种写法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
if(root==NULL) return {};
vector<int> ans;
stack<TreeNode*> s;
s.push(root);
while(!s.empty()){
TreeNode* cur = s.top(); s.pop();
if(cur!=NULL){
s.push(cur);
s.push(NULL);
if(cur->right) s.push(cur->right);
if(cur->left) s.push(cur->left);
}else{
ans.push_back(s.top()->val);
s.pop();
}
}
return ans;
}
};
这种写法本质上和上面的写法是一样的,都使用栈来模拟递归的过程,只是这种写法不需要额外的变量来进行标记,栈也是普通保存一个节点的栈,推荐这种写法。
- 时间复杂度:O(n)
- 空间复杂度:O(h)