标题: |
Construct Binary Tree from Preorder and Inorder Traversal |
通过率: | 26.5 |
难度: | 中等 |
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 4 \ 5 6前序为:12546中序为:25146
从前序得知第一个数一定是树的root,通过中序得到右树和左树
递归调用即可,其中要注意递归的条件个字符串拷贝时的用法,
具体看代码
1 /** 2 * Definition for binary tree 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==0||inorder.length==0){ 13 return null; 14 } 15 TreeNode root=new TreeNode(preorder[0]); 16 int i=0; 17 for(;i<inorder.length;i++){ 18 if(inorder[i]==preorder[0])break; 19 } 20 int [] new_pre_left,new_pre_right,new_in_left,new_in_right; 21 if(i<preorder.length){ 22 new_in_left=new int[i]; 23 System.arraycopy(inorder, 0, new_in_left, 0, i); 24 new_pre_left=new int[i]; 25 System.arraycopy(preorder, 1, new_pre_left, 0, i); 26 root.left=buildTree(new_pre_left,new_in_left); 27 28 new_in_right=new int[preorder.length-i-1]; 29 System.arraycopy(inorder, i+1, new_in_right, 0, preorder.length-i-1); 30 new_pre_right=new int[preorder.length-i-1]; 31 System.arraycopy(preorder, i+1, new_pre_right, 0, preorder.length-i-1); 32 root.right=buildTree(new_pre_right,new_in_right); 33 34 } 35 return root; 36 } 37 }
时间: 2024-11-17 09:52:43