Package com.cn.binarytree.utils;/** * @author Liu Lijuan [email protected] * @version created: July 20, 2014 2:03:30 class Description: */clas S node {node left; Node Right;char Chvalue; Node (char chvalue) {left = Null;right = Null;this.chvalue = Chvalue;}} public class Rebuild {public static final int treelen = 6;//number of nodes of the tree void Rebuild (char[] preorder, char[] inorder, int treel En, Node root) {if (preorder = = NULL | | inorder = = NULL) {//pre-sequence traversal sequence or middle sequence traversal sequence is empty return;} Node temp = new node (preorder[0]),//Gets the first node System.out.println ("Current node:" + preorder[0]) of the pre-sequence traversal sequence, if (root = null) {//Assuming the root node is NULL, the current node is copied to the root node, root = temp;} if (Treelen = = 1) {return;} int i = 0;while (i < inorder.length) {//Find node equal to preorder[0] in Inorder if (preorder[0]! = Inorder[i]) {i++;} else {break ;}} int leftlen = i; System.out.println ("left subtree length:" + leftlen); int rightlen = inorder.length-leftlen-1; System.out.println ("Right subtree length:" + Rightlen); if (Leftlen > 0) {for (int j = 0; J < Preorder.length-1; J + +) {Preorder[j] = preorder[j + 1];} char[] Leftorder = New Char[leftlen]; System.out.print ("Zuozi:"); for (int j = 0; J < Leftlen; J + +) {Leftorder[j] = inorder[j]; System.out.print (Leftorder[j] + "\ t");} System.out.println (); Rebuild (preorder, Leftorder, Leftlen, root.left);} if (Rightlen > 0) {for (int j = 0; J < Preorder.length-1; J + +) {Preorder[j] = preorder[j + 1];} char[] Rightorder = new Char[rightlen]; System.out.print ("Right sub-tree:"); for (int j = 0; J < Rightlen; J + +) {Rightorder[j] = inorder[j + Leftlen + 1]; System.out.print (Rightorder[j] + "\ t");} System.out.println (); Rebuild (preorder, Rightorder, Rightlen, root.right);}} public static void Main (string[] args) {char[] pre = {' A ', ' B ', ' d ', ' C ', ' e ', ' F '};char[] in = {' d ', ' B ', ' A ', ' e ', ' C ' ', ' F '};new Rebuild (). Rebuild (Pre, in, Treelen, null);}}Java implementation Reconstruction Binary tree: two fork tree traversal sequence and sequence sequencing traversal, binary reconstruction.
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
"The beauty of programming" Java Binary Implementation reconstruction