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].

 /**
* Definition for a binary tree node.
* 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> res;
help(root,res);
return res;
}
void help(TreeNode *root,vector<int> &res)
{
if(root!=NULL)
{
help(root->left,res);
help(root->right,res);
res.push_back(root->val);
}
}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> res;
stack<pair<TreeNode*,int>> s;
s.push(make_pair(root,));
while(!s.empty())
{
TreeNode *now=s.top().first;
if(now==NULL)
s.pop();
else
{
switch(s.top().second++)
{
case :
s.push(make_pair(now->left,));
break;
case :
s.push(make_pair(now->right,));
break;
default:
s.pop(); res.push_back(now->val);
break;
}
}
}
return res;
}
};
上一篇:【LeetCode题意分析&解答】33. Search in Rotated Sorted Array


下一篇:Cracking the coding interview--问题与解答