LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal

原题链接在这里:https://leetcode.com/problems/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.

题解:

利用preorder 和 inorder来构造树.

e.g. preorder 1, 2, 4, 5, 3, 6, 7

       inorder    4, 2, 5, 1, 6, 3, 7

先从preorder里去第一位, 是1, 1就是root.

在inorder里找到1, inorder里1左面的[4, 2, 5]就都是 1的左子树inorder,  inorder 里 1右面的[6, 3, 7]就都是1的右子树inorder.

因为[4,2,5]长度为三,在preorder 1 后面的 三个数[2,4,5]就是就是对应左子树的preorder, 在后面的三个数[3,6,7]就是对应右子树的preorder. 

重复上面的过程直到对应长度只有一个元素。

可以用HashMap来存储inorder对应的index, 省去每次找到对应点的时间.

Note: 1. Recursion终止条件是L>R 而不是L>=R, 因为只有一个元素时L=R,此时应该返回元素而不是返回null.

2. 题目中没有给其他的 TreeNode constructor, 所以不能用,例如TreeNode() 就不可以.

3. 采用help时, argument 要传HashMap<Integer, Integer> 不能省略<Integer, Integer>. Or it would throw error like Object could not be assigned to int. 

Time Complexity: O(n), 每个点访问一次. Space: O(n). HashMap.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode buildTree(int[] preorder, int[] inorder) {
12         if(preorder == null || preorder.length == 0 || inorder == null || inorder.length == 0){
13             return null;
14         }
15         HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
16         for(int i = 0; i<inorder.length; i++){
17             hm.put(inorder[i],i);
18         }
19         return helper(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1, hm);
20     }
21     private TreeNode helper(int[] preorder, int preL, int preR, int[] inorder, int inL, int inR, HashMap<Integer, Integer> hm){
22         if(preL > preR || inL > inR){
23             return null;
24         }
25         TreeNode root = new TreeNode(preorder[preL]);
26         int rootIndex = hm.get(preorder[preL]);
27         root.left = helper(preorder, preL+1, preL+rootIndex-inL, inorder, inL, rootIndex-1, hm);
28         root.right = helper(preorder, preL+rootIndex-inL+1, preR, inorder, rootIndex+1, inR, hm);
29         return root;
30     }
31 }

类似Construct Binary Tree from Inorder and Postorder TraversalConstruct Binary Tree from Preorder and Postorder Traversal.

posted @ 2015-08-21 02:33  Dylan_Java_NYC  阅读(290)  评论(0编辑  收藏  举报