题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
解题思路:
像这种题首选递归来做,一个大的数组拆分成不同的区域来做。
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 TreeNode root = reConstruct(pre,0,pre.length-1,in,0,in.length-1); 13 return root; 14 } 15 private TreeNode reConstruct(int [] pre, int startpre,int endpre,int [] in, int startin,int endin) 16 { 17 if(startpre>endpre || startin>endin) 18 { 19 return null; 20 } 21 22 TreeNode root = new TreeNode (pre[startpre]); 23 24 for(int i=startin; i<=endin;i++) 25 { 26 if(in[i]==pre[startpre]) 27 { 28 root.left = reConstruct(pre,startpre+1,startpre+i-startin,in,startin,i-1); 29 root.right = reConstruct(pre,startpre+i-startin+1,endpre,in,i+1,endin); 30 31 } 32 } 33 return root; 34 35 } 36 37 38 39 }
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 class Solution { 11 public TreeNode buildTree(int[] inorder, int[] postorder) { 12 TreeNode root = recon(inorder,0,inorder.length-1,postorder,0,postorder.length-1); 13 return root; 14 } 15 public TreeNode recon(int []inorder,int instart,int inend,int []postorder,int poststart,int postend) 16 { 17 if(instart>inend||poststart>postend) 18 return null; 19 20 TreeNode root = new TreeNode(postorder[postend]); 21 22 for(int i=instart;i<=inend;i++) 23 { 24 if(inorder[i]==postorder[postend]) 25 { 26 root.left = recon(inorder,instart,i-1,postorder,poststart,poststart+i-instart-1); 27 root.right = recon(inorder,i+1,inend,postorder,poststart+i-instart,postend-1); 28 } 29 } 30 return root; 31 } 32 }