1. 程式人生 > >#Leetcode# 106. Construct Binary Tree from Inorder and Postorder Traversal

#Leetcode# 106. Construct Binary Tree from Inorder and Postorder Traversal

https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

 

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

程式碼:

/**
 * 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:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return helper(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
    }
    TreeNode* helper(vector<int> &inorder, int ileft, int iright, vector<int> &postorder, int pleft, int pright) {
        if(ileft > iright || pleft > pright) return NULL;
        int i = 0;
        for(i = ileft; i < inorder.size(); ++ i)
            if(inorder[i] == postorder[pright]) break;
        TreeNode *cur = new TreeNode(postorder[pright]);
        cur -> left = helper(inorder, ileft, i - 1, postorder, pleft, pleft + i - ileft -1);
        cur -> right = helper(inorder, i + 1, iright, postorder, pleft + i - ileft, pright - 1);
        
        return cur;
    }
};

  終於搞完了期末大作業剩下的就只有考試了 可愛 Be 主又每天線上10h + 激情刷題了 工作日倒數第二天 要迎接元旦假期了呢