102. Binary Tree Postorder Traversal
Description:
Given a binary tree, return the postorder traversal of its nodes’ values.
Difficulty:hard
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
方法1:Iterative
- Time complexity : O ( n ) O\left ( n\right ) O(n)
- Space complexity :
O
(
n
)
O\left ( n \right )
O(n)
思路:
非递归后序遍历
先将左边全部push到栈
如果top的右节点不为空且不是上一次pop出来的节点,cur指向右节点进行下一次循环,否则pop出top,更新last_pop
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> s;
TreeNode *cur = root;
TreeNode *last_pop = NULL;
while(cur != NULL || !s.empty()){
while(cur != NULL){
s.push(cur);
cur = cur->left;
}
TreeNode* top = s.top();
if(top->right != NULL && top->right != last_pop)
cur = top->right;
else{
res.push_back(top->val);
last_pop = top;
s.pop();
}
}
return res;
}
};
方法1:Reserve
- Time complexity : O ( n ) O\left ( n\right ) O(n)
- Space complexity :
O
(
n
)
O\left ( n \right )
O(n)
思路:
非递归后序遍历
后续遍历是左-右-根
,我们可以先找到根-右-左
的解,再反转数组即可。
先将根push,
循环内:pop出来top,如果top有左节点就push,如果top有右节点就push,进入下次循环 注意push是先进左再进右,pop的时候就是先右再左了
最后反转答案
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> s;
s.push(root);
while(!s.empty()){
TreeNode *cur = s.top();
res.push_back(cur->val);
s.pop();
if(cur->left != NULL)
s.push(cur->left);
if(cur->right != NULL)
s.push(cur->right);
}
reverse(res.begin(), res.end());
return res;
}
};