Title Description:
To enter the results of the pre-order traversal and the middle sequence traversal of a binary tree, rebuild the two-fork tree. Assume that no duplicate numbers are included in the result of the input's pre-order traversal and the middle-order traversal. For example, enter the pre-sequence traversal sequence {1,2,4,7,3,5,6,8} and the middle sequence traversal sequence {4,7,2,1,5,3,8,6}, then rebuild the binary tree and return.
Public classTest {/** Binary tree node class*/ classTreeNode {intVal; TreeNode left; TreeNode right; TreeNode (intx) { This. val =x; } } /** The binary tree is reconstructed by the pre-sequence traversal and the middle sequence traversal of a given binary tree. Assuming that both the pre-order traversal and the middle-order traversal have no duplicate numbers*/ /** * * @paramPre pre-order traversal *@paramin middle order traversal *@returntwo fork root node*/ PublicTreeNode Reconstructbinarytree (int[] Pre,int[] in) { /** input legitimacy judgment, can not be empty, the first order and the sequence length should be consistent*/ if(Pre = =NULL|| in = =NULL|| Pre.length! =in.length)return NULL; returnConstruct (pre, 0, Pre.length-1, in, 0, in.length-1); } /** * * @paramPre pre-order traversal *@paramstarting position of PS pre-sequence traversal *@paramEnd position of PE pre-order traversal *@paramin middle order traversal *@paramis the starting position of the sequence traversal *@paramend position of the sequence traversal in IE *@returnthe root node of the number*/ PrivateTreeNode Construct (int[] Pre,intPsintPeint[] in,intIS,intIE) { if(PS > PE)return NULL; //the first number that takes a pre-order traversal is the root node intValue =Pre[ps]; //finding the root node in the middle sequence traversal intindex =is ; while(Index <= IE && value! =In[index]) {Index++; } //if it is not found in the entire middle sequence traversal, the argument entered is illegal and throws an exception if(Index >IE)Throw NewRuntimeException ("Invalid iuput!"); //creates the current root node and assigns a value to the root nodeTreeNode node =NewTreeNode (value); //recursive call to build the left subtree of the current nodeNode.left = construct (pre, ps+1, Ps+index-is, in, is, index-1); //recursive call to build the right subtree of the current nodeNode.right = construct (pre, ps+index-is+1, PE, IN, index+1, IE); returnnode; } Private voidprinttree (TreeNode root) {if(Root! =NULL) {printtree (root.left); System.out.println (Root.val+ " "); Printtree (Root.right); } } Public Static voidMain (string[] args) {test test=NewTest (); int[] pre = {1, 2, 4, 7, 3, 5, 6, 8}; int[] in = {4, 7, 2, 1, 5, 3, 8, 6}; TreeNode node=Test.reconstructbinarytree (pre, in); Test.printtree (node); } }
Offer-of the sword to reconstruct the two-fork tree