Problem
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, the binary tree is rebuilt by entering 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}.
Ideas
First we find the first node of the first order traversal, which is the root node, and then find the root node in the middle sequence traversal. At this point, the left and right sides of the root node, respectively, are the middle sequence traversal of the subtree. Then for the first order traversal, starting from the second node, the length of the left subtree in the middle sequence traversal is the Zuozi of the first order traversal. Similarly, the right subtree is the same, which is a recursive process.
PublicBinarytreenode Gettheroot (list<integer>Preorder, List<Integer> Inorder,intcount) { //The first number in the pre-order arrangement is the value of the current root node intRootvalue = Preorder.get (0); Binarytreenode Root=NewBinarytreenode (); Root.value=Rootvalue; //if count=1, indicates that the current node is a leaf node and returns directly if(Count = = 1) { returnRoot; } //position of the value of the root node in the middle order arrangement intindex = 0; for(intI:inorder) { if(i = =rootvalue) { Break; } Index++; } //Indicates that the value of the root node is not found in the ordinal arrangement, which indicates that the input in the pre-order or the middle order is incorrect if(Index = =count) { Throw NewRuntimeException ("wrong sort input!")); } //If index > 0, it indicates that there is currently a left dial hand tree if(Index > 0) { //the pre-order arrangement of the Zuozi starts with the second value (minus the current root node) of the current pre-order, and contains the left subtree number values (index)list<integer> Startpreorder = preorder.sublist (1, (index + 1)); //The Zuozi of an array begins with the first value in the current middle order, until the root node is located (without the root node)list<integer> startinorder = inorder.sublist (0, index); Root.left=gettheroot (Startpreorder, Startinorder, index); } //If index > 0, it indicates that there is currently a subtree if(Index < Count-1) {List<Integer> Endpreorder = preorder.sublist (index + 1), count); List<Integer> Endinorder = inorder.sublist (index + 1), count); //Why is count-index-1 here? You can draw some thought .Root.right = Gettheroot (Endpreorder, Endinorder, (count-index-1)); } returnRoot; }Summarize
First, we should be familiar with the binary tree's pre-sequence traversal, the middle sequence traversal, and the post-order traversal, coupled with the idea of recursion, can be realized.
Rebuilding a binary tree