The post order is very hard to implement but the pre - order is much easier;
pre-order::
/**
* 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> preorderTraversal(TreeNode *root) {
vector<int> result;
if(!root) return result;
stack<TreeNode *> stk;
stk.push(root);
TreeNode *nd=NULL;
while(!stk.empty())
{
nd = stk.top();
stk.pop();
result.push_back(nd->val);
if(nd->right)
{
stk.push(nd->right);
}
if(nd->left)
{
stk.push(nd->left);
}
}
}
};
but as the post order is totally the reserve of the pre order so we can use a stack to reverse it ;
we have to make the right one into the stk;
HLR ->(try to visit the right child firstly)-> HRL -> (reverse it using a stack)->LRH
/**
* 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) {
vector<int> result;
if(root == NULL) return result;
stack<TreeNode *> preoderStk;
stack<int> resultStk;
preoderStk.push(root);
while(!preoderStk.empty())
{
TreeNode *nd = preoderStk.top();
resultStk.push(nd->val);
preoderStk.pop();
if(nd->left)
{
preoderStk.push(nd->left);
}
if(nd->right)
{
preoderStk.push(nd->right);
}
}
while(!resultStk.empty())
{
result.push_back(resultStk.top());
resultStk.pop();
}
return result;
}
};