[LeetCode]Binary Tree Postorder Traversal
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?
思考:原思路是为每个节点增加一个标记。这个思路先序遍历不要标记,因为当前访问结点直接出栈,不用看是否访问过。不过此思路redefinition of 'struct TreeNode'。
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
bool flag;
TreeNode(int x) : val(x), left(NULL), right(NULL), flag(false) {}
};
class Solution {
private:
vector<int> ret;
public:
vector<int> postorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ret.clear();
if(!root) return ret;
stack<TreeNode *> s;
s.push(root);
while(!s.empty())
{
TreeNode *cur=s.top();
if(cur->left&&!cur->left->flag)
s.push(cur->left);
else if(cur->right&&!cur->right->flag)
s.push(cur->right);
else
{
ret.push_back(cur->val);
cur->flag=true;
s.pop();
}
}
return ret;
}
};
既然不能增加标记结点,那么遍历过的结点直接“删掉”。不过这么做破坏了原树结构。
class Solution {
private:
vector<int> ret;
public:
vector<int> postorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ret.clear();
if(!root) return ret;
stack<TreeNode *> s;
s.push(root);
TreeNode *cur=s.top();
while(!s.empty())
{
TreeNode *cur=s.top();
if(!cur->left&&!cur->right)
{
ret.push_back(cur->val);
s.pop();
}
if(cur->right)
{
s.push(cur->right);
cur->right=NULL;
}
if(cur->left)
{
s.push(cur->left);
cur->left=NULL;
}
}
return ret;
}
};
网上搜索有没有更好的方法,发现自己思维定势了,只知道不能递归就用stack代替。参考http://www.cnblogs.com/changchengxiao/p/3416402.html

浙公网安备 33010602011771号