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?
Recursive:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void postOrder(TreeNode* root, vector<int> &path)
{
if(root!=NULL)
{
postOrder(root->left, path);
postOrder(root->right, path);
path.push_back(root->val);
}
}
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.
vector<int> path;
postOrder(root, path);
return path;
}
};
Iterative:
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
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;
}
};