二叉樹重建-遞迴
阿新 • • 發佈:2020-12-28
package JianZhioffer; // 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。 //遞迴,進入helperZ之前用整體進入後分左右 public class test07 { public static void main(String[] args) { int []preorder={3,9,20,15,7}; int []inorder={9,3,15,20,7}; TreeNode tr=buildTree(preorder, inorder); int x=0; }public static TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder.length==0||inorder.length==0){ return null; } TreeNode result=helper(0, preorder.length-1, 0,inorder.length-1,preorder, inorder); return result; } public static TreeNode helper(intprestart,int preend,int instart,int inend,int []preorder,int []inorder){ if( prestart>preend){ return null; } TreeNode tr=new TreeNode(preorder[prestart]); if(prestart==preend){ return tr; } int r=preorder[prestart];int k=0; for(int i=instart;i<=inend;i++){ if(inorder[i]==r){ k=i; break; } } int x=k-instart; int y=inend-k; tr.left=helper(prestart+1, prestart+x,instart,k-1, preorder, inorder); tr.right=helper(preend-y+1, preend,k+1,inend, preorder, inorder); return tr; } }