Construct Binary Tree from Preorder and Inorder Traversal

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

 

 

 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.length != inorder.length) {
13             return null;
14         }
15         return helper(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
16     }
17     private TreeNode helper(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {
18         if (preStart > preEnd) {
19             return null;
20         }
21         TreeNode root = new TreeNode(preorder[preStart]);
22         int position = findPosition(inorder, inStart, inEnd, preorder[preStart]);
23         root.left = helper(preorder, preStart + 1, preStart + position - inStart, inorder, inStart, inStart + position - inStart - 1);
24         root.right = helper(preorder, preStart + position - inStart + 1, preEnd, inorder, inStart + position - inStart + 1, inEnd);
25         return root;
26     }
27     private int findPosition(int[]nums, int start, int end, int key) {
28         int i = 0;
29         for (i = start; i <= end; i++) {
30             if (nums[i] == key) {
31                 return i;
32             }
33         }
34         return -1;
35     }
36 }

 

posted @ 2016-04-28 09:40  YuriFLAG  阅读(123)  评论(0)    收藏  举报