美文网首页
Binary Tree Postorder Traversal

Binary Tree Postorder Traversal

作者: 一枚煎餅 | 来源:发表于2016-09-19 09:35 被阅读0次
    Binary Tree Postorder Traversal.png

    解題思路 :

    1. post order 的 recursive 解法 left, right, self
    2. 如果要使用 iterative 的做法 可以用 stack 來做 放進 stack 的順序為 left, right 這樣 pop 出來檢查的時候就會相反先拿到 right 的值 等全部走完在最後 reverse 一次得到的結果 就是正確解

    C++ code :

    <pre><code>
    //Recursive

    class Solution {

    /**
     * @param root: The root of binary tree.
     * @return: Postorder in vector which contains node values.
     */
    

    public:

    void PostOrder(TreeNode *root, vector<int> &res)
    {
        if(root == nullptr) return;
        PostOrder(root->left, res);
        PostOrder(root->right, res);
        res.emplace_back(root->val);
    }
    
    vector<int> postorderTraversal(TreeNode *root) {
        // write your code here
        vector<int> res;
        PostOrder(root, res);
        return res;
    }
    

    };

    //Non-Recursive

    class Solution {

    /**
     * @param root: The root of binary tree.
     * @return: Postorder in vector which contains node values.
     */
    

    public:

    void reverse(vector<int> &res)
    {
        int start = 0;
        int end = res.size() - 1;
        while(start <= end)
        {
            int tmp = res[start];
            res[start] = res[end];
            res[end] = tmp;
            start++;
            end--;
        }
    }
    
    vector<int> postorderTraversal(TreeNode *root) {
        // write your code here
        vector<int> res;
        if(root == nullptr) return res;
        stack<TreeNode*> S;
        S.push(root);
        while(!S.empty())
        {
            TreeNode *tmp = S.top();
            S.pop();
            res.push_back(tmp->val);
            if(tmp->left) S.push(tmp->left);
            if(tmp->right) S.push(tmp->right);
        }
        reverse(res);
        return res;
    }
    

    };

    相关文章

      网友评论

          本文标题:Binary Tree Postorder Traversal

          本文链接:https://www.haomeiwen.com/subject/vfngettx.html