题目
Given a binary tree, return the postorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
求二叉树的后序遍历结果,用循环不用递归
代码
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();
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;
}
};