首页 > 代码库 > Construct Binary Tree From Preorder and Inorder Traversal

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 /**
 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) return null;
13         
14         int preLeft = 0, preRight = preorder.length - 1, inLeft = 0, inRight = inorder.length -1;
15         return buildTree(preorder, inorder, preLeft, preRight, inLeft, inRight);
16     }
17     
18     private TreeNode buildTree(int[] preorder, int[] inorder, int preLeft, int preRight, int inLeft, int inRight) {
19         if (preLeft > preRight) return null;
20         
21         TreeNode temp = new TreeNode(preorder[preLeft]);
22         if (preLeft == preRight)
23             return temp;
24         
25         int index = inLeft;
26         while (index < inRight && inorder[index] != preorder[preLeft])
27             index++;
28             
29         temp.left = buildTree(preorder, inorder, preLeft + 1, preLeft + index - inLeft, inLeft, index - 1);
30         temp.right = buildTree(preorder, inorder, preLeft + index - inLeft + 1, preRight, index + 1, inRight);
31         return temp;
32     }
33 }

 

Construct Binary Tree From Preorder and Inorder Traversal