19.3.5 [LeetCode 105] Construct Binary Tree from Preorder and Inorder Traversal

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

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

For example, given

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

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7
 1 class Solution {
 2 public:
 3     int p1;
 4     TreeNode*buildchild(vector<int>& preorder, vector<int>& inorder, int i1, int i2) {
 5         if (i2 < i1)
 6             return NULL;
 7         int nowroot = preorder[p1];
 8         TreeNode*ans = new TreeNode(nowroot);
 9         for (int i = i1; i <= i2; i++)
10             if (inorder[i] == nowroot) {
11                 if (i != i1) {
12                     ++p1;
13                     ans->left = buildchild(preorder, inorder, i1, i - 1);
14                 }
15                 if (i != i2) {
16                     ++p1;
17                     ans->right = buildchild(preorder, inorder, i + 1, i2);
18                 }
19             }
20         return ans;
21     }
22     TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
23         p1 = 0;
24         return buildchild(preorder, inorder, 0, inorder.size() - 1);
25     }
26 };
View Code

 

注定失败的战争,也要拼尽全力去打赢它; 就算输,也要输得足够漂亮。
posted @ 2019-03-05 11:08  TobicYAL  阅读(152)  评论(0编辑  收藏  举报