题目:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
解题思路分析:
前序遍历首先遍历根节点,然后依次遍历左右子树
中序遍历首先遍历左子树,然后遍历根结点,最后遍历右子树
根据二者的特点,前序遍历的首节点就是根结点,然后在中序序列中找出该结点位置(index),则该结点之前的为左子树结点,该节点之后为右子树结点;
同样对于前序序列,首结点之后的index个结点为左子树结点,剩余的节点为右子树结点;
最后,递归建立子树即可。
java代码:
1 public class Solution { 2 public TreeNode buildTree(int[] preorder, int[] inorder) { 3 if(preorder == null || preorder.length == 0){ 4 return null; 5 } 6 7 int flag = preorder[0]; 8 TreeNode root = new TreeNode(flag); 9 int i = 0; 10 for(i=0; i<inorder.length; i++){ 11 if(flag == inorder[i]){ 12 break; 13 } 14 } 15 16 int[] pre_left, pre_right, in_left, in_right; 17 pre_left = new int[i]; 18 for(int j=1; j<=i;j++){ 19 pre_left[j-1] = preorder[j]; 20 } 21 pre_right = new int[preorder.length-i-1]; 22 for(int j=i+1; j<preorder.length;j++){ 23 pre_right[j-i-1] = preorder[j]; 24 } 25 26 in_left = new int[i]; 27 for(int j=0;j<i;j++){ 28 in_left[j] = inorder[j]; 29 } 30 in_right = new int[inorder.length-i-1]; 31 for(int j=i+1; j<inorder.length; j++){ 32 in_right[j-i-1] = inorder[j]; 33 } 34 root.left = buildTree(pre_left,in_left); 35 root.right = buildTree(pre_right,in_right); 36 37 38 39 return root; 40 41 } 42 43 44 }