茕&茕 剑指offer——重建二叉树
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
代码实现(Java)
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 reConstructBinaryTree(int [] pre,int [] in) { 12 if(pre==null || in==null){ 13 return null; 14 } 15 if(pre.length!=in.length){ 16 System.out.println("长度不一样,非法输入"); 17 } 18 return reConBTree(pre,0,pre.length-1,in,0,in.length-1); 19 } 20 public TreeNode reConBTree(int[] pre,int preLeft,int preRight,int[] in,int inLeft,int inRight){ 21 if(preLeft>preRight || inLeft>inRight){ 22 return null; 23 } 24 TreeNode root=new TreeNode(pre[preLeft]); 25 for(int i=inLeft;i<=inRight;i++){ 26 if(pre[preLeft]==in[i]){ 27 root.left=reConBTree(pre,preLeft+1,preLeft+i-inRight,in,inLeft,i-1); 28 root.right=reConBTree(pre,preLeft+i-inRight+1,preRight,in,i+1,inRight); 29 } 30 } 31 return root; 32 } 33 }
posted on 2019-10-29 19:07 Joyce&wang 阅读(136) 评论(0) 收藏 举报
浙公网安备 33010602011771号