Note: (1) construction of tree in Java
(2) The subtree can be built directly using Arrays.copyofrange (preorder, from, to), this method is left open right closed
1 PackageCom.xsf.SordForOffer;2 3 Importjava.util.Arrays;4 5 /*The 6th question of the point of the sword6 reconstruction of Binary tree based on pre-order and middle sequence traversal7 */8 classBinarytreenode {9 Public intvalue;Ten PublicBinarytreenode Leftnode; One PublicBinarytreenode Rightnode; A } - - classConstructcore { the /* - * Input binary tree pre-sequence traversal and middle sequence traversal results, reconstruct the binary tree and lose the node ex:12473568,47215386 - */ - PublicBinarytreenode Constructcore (int[] Preorder,int[] inorder) + throwsException { - + if(Preorder = =NULL|| Inorder = =NULL) { A return NULL; at } - if(Preorder.length! =inorder.length) { - Throw NewException ("Not the same length-illegal input"); - } -Binarytreenode root =NewBinarytreenode (); - for(inti = 0; i < inorder.length; i++) { in if(Inorder[i] = = Preorder[0]) { - //Ishave = true; toRoot.value =Inorder[i]; +Root.leftnode =Constructcore ( -Arrays.copyofrange (preorder, 1, i + 1), theArrays.copyofrange (inorder, 0, i)); *Root.rightnode =Constructcore ( $Arrays.copyofrange (Preorder, i + 1, preorder.length),Panax NotoginsengArrays.copyofrange (inorder, i + 1, Inorder.length)); - } the } + A returnRoot; the } + - Public voidLastordertraverse (Binarytreenode T) { $ if(T! =NULL) { $ Lastordertraverse (t.leftnode); - Lastordertraverse (t.rightnode); - System.out.print (t.value); the } - }Wuyi } the - Public classpro6biconstruct { Wu Public Static voidMain (string[] args)throwsException { -Constructcore test =NewConstructcore (); About int[] pre = {1, 2, 4 }; $ int[] in = {2, 1, 4 }; -Binarytreenode root =Test.constructcore (pre, in); - Test.lastordertraverse (root); - } A}
Pro 6 Rebuilding a binary tree (Java)