【LeetCode】145. Binary Tree Postorder Traversal (3 solutions)

weixin_34126215發表於2014-11-14

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> ret;
        Helper(ret, root);
        return ret;
    }
    void Helper(vector<int>& ret, TreeNode* root)
    {
        if(root != NULL)
        {
            Helper(ret, root->left);
            Helper(ret, root->right);
            ret.push_back(root->val);
        }
    }
};

 

解法二:藉助棧的深度優先搜尋,需要記錄每個節點是否訪問過。

/**
 * 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> ret;
        if(root == NULL)
            return ret;
        stack<TreeNode*> stk;
        unordered_map<TreeNode*, bool> visited;
        stk.push(root);
        visited[root] = true;
        while(!stk.empty())
        {
            TreeNode* top = stk.top();
            if(top->left != NULL && visited[top->left] == false)
            {
                stk.push(top->left);
                visited[top->left] = true;
                continue;
            }
            if(top->right != NULL && visited[top->right] == false)
            {
                stk.push(top->right);
                visited[top->right] = true;
                continue;
            }
            ret.push_back(top->val);
            stk.pop();
        }
        return ret;
    }
};

 

解法三:在Discussion看到一種巧妙的解法。

前序是:根左右

後序是:左右跟

因此可以將前序改為根右左,然後逆序為左右根輸出。

前序遍歷不需要回溯(對應圖的深度遍歷),是一種半層次遍歷,因此效率很高。

/**
 * 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> ret;
        if(root == NULL)
            return ret;
        stack<TreeNode*> stk;
        stk.push(root);
        while(!stk.empty())
        {
            TreeNode* top = stk.top();
            stk.pop();
            ret.push_back(top->val);
            if(top->left != NULL)
                stk.push(top->left);
            if(top->right != NULL)
                stk.push(top->right);
        }
        reverse(ret.begin(), ret.end());
        return ret;
    }
};

相關文章