1. 程式人生 > >Binary Tree Postorder Traversal 非遞迴實現二叉樹後序遍歷

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?

/**
 * 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;
        if(root==NULL)
            return res;
       
        stack<TreeNode *> vis;
        stack<TreeNode *> travel;
        
        travel.push(root);
        while(!travel.empty()){
            TreeNode *tmp=travel.top();
            travel.pop();
            
            vis.push(tmp);
            if(tmp->left)
                travel.push(tmp->left);
            if(tmp->right)
                travel.push(tmp->right);
        }
        
        while(!vis.empty()){
            TreeNode *tmp=vis.top();
            vis.pop();
            res.push_back(tmp->val);
        }
        return res;
    }
};