Binary Tree Postorder Traversal

2016-09-19  本文已影响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;
}

};

上一篇下一篇

猜你喜欢

热点阅读