[面试真题] LeetCode: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.

解法:递归求解。

  基本情况:先序与中序数组长度小于1时,返回NULL。

  递归步骤:首先确定preorder的第一个元素一定是该树的root,再在inorder中找到该元素,标记为index,index左部为左子树的中序,右部为右子树的中序;随后通过左右子树中序的长度(可能为0),在preorder中确定左右子树的先序。

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11     TreeNode *buildTree(vector<int> &preorder,int ph, int pe, vector<int> &inorder, int ih, int ie){
12         TreeNode *root;
13         if(pe - ph < 0){
14             return NULL;
15         }
16         root = new TreeNode(preorder[ph]);
17         int index = ih-1;
18         while(++index <= ie && inorder[index] != preorder[ph]){
19         }
20         int leftPreLen = index - ih;
21         root->left = buildTree(preorder, ph+1, ph+leftPreLen, inorder, ih, index-1);
22         root->right = buildTree(preorder, ph+leftPreLen+1, pe, inorder, index+1, ie);
23         return root;
24     }
25     
26 public:
27     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
28         // Start typing your C/C++ solution below
29         // DO NOT write int main() function
30         return buildTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
31         
32     }
33 };

 

Run Status: Accepted!
Program Runtime: 164 milli secs

你可能感兴趣的:(LeetCode)