LeetCode

Construct Binary Tree from Preorder and Inorder Traversal

2014.1.8 00:59

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

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

Solution:

  preorder traversal = root, left, right;

  inorder traversal = left, root, right;

  Thus the first element in the preorder sequence is the root. Find it in the inorder sequence and you know where the left and right subtrees are. Do this procedure recursively and the job is done.

  Time and space complexities are both O(n), where n is the number of nodes in the tree. The space complexity comes from the local parameters passed in function calls.

Accepted code:

 1 // 1AC, excellent!!!
 2 /**
 3  * Definition for binary tree
 4  * struct TreeNode {
 5  *     int val;
 6  *     TreeNode *left;
 7  *     TreeNode *right;
 8  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 9  * };
10  */
11 class Solution {
12 public:
13     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
14         // IMPORTANT: Please reset any member data you declared, as
15         // the same Solution instance will be reused for each test case.
16         return recoverTree(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
17     }
18 private:
19     TreeNode *recoverTree(vector<int> &preorder, vector<int> &inorder, int l1, int r1, int l2, int r2) {
20         if(l1 > r1){
21             return nullptr;
22         }
23         
24         if(l2 > r2){
25             return nullptr;
26         }
27         
28         TreeNode *root = new TreeNode(preorder[l1]);
29         int i;
30         
31         for(i = l2; i <= r2; ++i){
32             if(inorder[i] == root->val){
33                 break;
34             }
35         }
36         
37         root->left = recoverTree(preorder, inorder, l1 + 1, (l1 + 1)  + (i - 1 - l2), l2, i - 1);
38         root->right = recoverTree(preorder, inorder, r1 - (r2 - i - 1), r1, i + 1, r2);
39         
40         return root;
41     }
42 };
原文地址:https://www.cnblogs.com/zhuli19901106/p/3509986.html