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.
[解题思路]
由前序遍历知第一个节点是根节点,根据此节点值去中序遍历集合中找该root值所处位置,
该位置之前的数属于左子树,之后的属于右子树,即找到左子树和右子树所处的子序列,接下来就可以用递归来完成
递归的终止条件:preorder中仅有一个元素且preorder中的元素和inorder中元素相同
1 /** 2 * @author rgc 3 * @date 2013-8-23上午10:07:40 4 * @version 1.0 5 */ 6 public class Solution { 7 8 public static void main(String[] args) { 9 int[] preorder = new int[]{1,2,3}; 10 int[] inorder = new int[]{1,2,3}; 11 buildTree(preorder, inorder); 12 } 13 14 public static TreeNode buildTree(int[] preorder, int[] inorder) { 15 // Start typing your Java solution below 16 // DO NOT write main() function 17 if (preorder == null || inorder == null) { 18 return null; 19 } 20 int preLen = preorder.length; 21 int inLen = inorder.length; 22 if (preLen == 0 || inLen == 0) { 23 return null; 24 } 25 26 return constructTree(preorder, 0, preLen - 1, inorder, 0, inLen - 1); 27 } 28 29 public static TreeNode constructTree(int[] preorder, int preStart, int preEnd, 30 int[] inorder, int inStart, int inEnd) { 31 int rootValue = preorder[preStart]; 32 TreeNode root = new TreeNode(rootValue); 33 root.left = null; 34 root.right = null; 35 if (preStart == preEnd && preorder[preStart] == inorder[inStart]) { 36 return root; 37 } 38 39 int i = inStart; 40 for (; i <= inEnd; i++) { 41 if (rootValue == inorder[i]) { 42 break; 43 } 44 } 45 int leftLen = i - inStart; 46 // exsit left subtree 47 if (leftLen > 0) { 48 root.left = constructTree(preorder, preStart + 1, preStart 49 + leftLen, inorder, inStart, i - 1); 50 } 51 if (inEnd > i) { 52 root.right = constructTree(preorder, preStart + leftLen + 1, 53 preEnd, inorder, i + 1, inEnd); 54 } 55 return root; 56 } 57 58 } 59 60 class TreeNode { 61 int val; 62 TreeNode left; 63 TreeNode right; 64 65 TreeNode(int x) { 66 val = x; 67 } 68 }