145. Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [3,2,1]

Follow up: 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) {
        if (root==NULL)
            return vector<int> ();
        TreeNode *Pcur, *Plast;
        vector<int> result;
        stack<TreeNode*> treestack;
        Pcur = root;
        Plast = NULL;
        while(Pcur){
            treestack.push(Pcur);
            Pcur = Pcur->left;
        }
        while(!treestack.empty()){
            Pcur = treestack.top();
            treestack.pop();
            //Only condition to print
            if(Pcur->right==NULL||Pcur->right==Plast){
                Plast = Pcur;
                result.push_back(Pcur->val);
            }
            else{
                treestack.push(Pcur);
                Pcur = Pcur->right;
                while(Pcur){
                    treestack.push(Pcur);
                    Pcur = Pcur->left;
                }
            }    
        }
        return result;
    }
};

非遞歸的二叉樹後序遍歷,要點是設置兩個結點指針,一個是current結點,一個是last結點。將current結點先置於最左節點上。然後開始進行循環,判斷能夠輸出的唯一條件是,current結點的右子樹爲空或者右子樹是上一個被訪問過的結點,也就是last結點。如果不滿足條件,就重新將current結點入棧,且讓current結點走到右子樹的最左端,其他結點也依次入棧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章