145. Binary Tree Postorder Traversal
problem description
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
algorithm thought
递归方法就不说了,对于迭代方法,这里只用一个栈还是不好理解,需要但是换种思路,后序遍历的逆序,其实就是先序遍历的先遍历右节点版本。 我们只需要将之前的先序遍历算法,从 根->左->右 改为 根->右->左。得到最后结果之后,将结果逆序即可。
code
/**
* 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) {
vector<int> res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* tmp=st.top();
st.pop();
while(tmp){
res.push_back(tmp->val);
st.push(tmp->left);
tmp=tmp->right;
}
}
reverse(res.begin(),res.end());
return res;
}
};
algorithm analysis
时间复杂度O(n),空间复杂度O(n)。其实后序遍历也是有Morris算法的,但是我觉得有点麻烦,可能这种reverse的方法更好。
Last updated