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> path;
if(root==NULL)return path;
stack<TreeNode*> stk;
stk.push(root);//将根节点入栈
TreeNode* cur = NULL;
while(!stk.empty())//如果栈非空
{
cur = stk.top();//将cur指向当前栈首。
//如果左右子树为空,
if(cur->left ==NULL && cur->right ==NULL)
{
path.push_back(cur->val);//如果左右子树都处理过,就表示栈为空
stk.pop();
}else{
if(cur->right)//如果存在右子树,这里先右子树入栈。
{
stk.push(cur->right);
cur->right = NULL;//表示根节点右子树处理
}
if(cur->left)//如果存在左子树。
{
stk.push(cur->left);
cur->left = NULL;//表示跟节点左子树处理过
}
}
}
return path;
}
};