輸入某二叉樹的前序走訪和中序遍曆的結果,請重建出該二叉樹。假設輸入的前序走訪和中序遍曆的結果中都不含重複的數字。例如輸入前序走訪序列{1,2,4,7,3,5,6,8}和中序遍曆序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
java實現代碼:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */import java.util.ArrayList;public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if(pre==null && in==null) return null; TreeNode root=new TreeNode(pre[0]); int left_length=0; int right_length=0; for(int i=0;i<in.length;i++){ if(in[i]==pre[0]){ break; }else{ left_length++; } } right_length=in.length-left_length-1; if(left_length!=0){ int prel[]=new int[left_length]; int inl[]=new int[left_length]; for(int i=0;i<left_length;i++){ prel[i]=pre[i+1]; inl[i]=in[i]; } root.left=reConstructBinaryTree(prel,inl); } else{ root.left=null; } if(right_length!=0){ int prer[]=new int[right_length]; int inr[]=new int[right_length]; int count=0; for(int i=right_length;i>0;i--){ prer[count]=pre[pre.length-i]; inr[count]=in[pre.length-i]; count++; } root.right=reConstructBinaryTree(prer,inr); ; } else{ root.right=null; } return root; }}