问题:链接
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?
解答:要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。如果P不存在左孩子和右孩子,则可以直接访问它;或者P存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该结点。若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。
采用pre 记录上一个被访问的节点代表左右子树,依据是: 左右子节点一定是和父节点相邻访问。
参考:http://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html
代码:
/**
* 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) {
stack<TreeNode*> st;
vector<int> result;
if(root != NULL)
st.push(root);
TreeNode *pre = NULL;
TreeNode *cur;
while(!st.empty())
{
cur = st.top();
if((cur->left == NULL && cur->right == NULL) ||(pre != NULL &&(pre == cur->left || pre == cur->right)))
{
result.push_back(cur->val);
st.pop();
pre = cur;
}
else
{
if(cur->right != NULL)
st.push(cur->right);
if(cur->left != NULL)
st.push(cur->left);
}
}
return result;
}
};