/**
* 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*> s;
vector<int> result;
TreeNode *cur; //当前结点
TreeNode *pre=NULL; //前一次访问的结点
if(root)
{
s.push(root);
}
while(!s.empty())
{
cur=s.top();
if((cur->left==NULL&&cur->right==NULL)||
(pre!=NULL&&(pre==cur->left||pre==cur->right)))
{
// cout<<cur->data; //如果当前结点没有孩子结点或者孩子节点都已被访问过
result.push_back(cur->val);
s.pop();
pre=cur;
}
else
{
if(cur->right!=NULL)
s.push(cur->right);
if(cur->left!=NULL)
s.push(cur->left);
}
}
return result;
}
};
【LeetCode】Binary Tree Postorder Traversal
最新推荐文章于 2022-07-19 11:52:33 发布