题目描述
求给定的二叉树的后序遍历。
例如:
给定的二叉树为{1,#,2,3},
1↵ ↵ 2↵ /↵ 3↵
返回[3,2,1].
备注;用递归来解这道题太没有新意了,可以给出迭代的解法么?
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree{1,#,2,3},
1↵ ↵ 2↵ /↵ 3↵
return[3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
解题思路
将前序遍历根左右改成根右左,再倒过来就是左右根。
/**
* Definition for binary tree
* 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> list;
if(root == NULL)
return list;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){ //将根左右变成根右左
TreeNode *temp = st.top();
st.pop();
list.push_back(temp->val);
if(temp->left)
st.push(temp->left);
if(temp->right)
st.push(temp->right);
}
reverse(list.begin(), list.end());
return list;
}
};