Home » Java » At offer programming (four)

At offer programming (four)

Title Description:

Preorder traversal enter a two binary tree and traversal of the results, please. The reconstruction of two binary tree preorder traversal and traversal of the input hypothesis results do not contain duplicate numbers. For example, enter the first traversal sequence traversal sequence {1,2,4,7,3,5,6,8} and {4,7,2,1,5,3,8,6}, the reconstruction of two binary tree traversal.

and subsequent return

ideas: typically know before the order and in order to seek the two tree problem, first look at the preorder traversal, preorder traversal according to rules can know the root node of the two fork tree first element, other elements for the root node number. The node pre order traversal in the traversal, find the node, then the node is on the left of the tree left sub tree, the tree on the right is the right subtree. For example: the first element of preorder traversal is 1, then the traversal found in 1, so the tree left sub tree the elements are {4,7,2}, right subtree of the elements is {5,3,8,6}, then the following can be solved recursively each sub tree, for example, the left sub tree in preorder traversal in {4,7,2}, in order to find the 2, then the subtree of the left subtree is {4,7}, the right subtree is empty for {}, according to this method. Recursively find it, then You can build a two fork tree. The following code is the output sequence traversal of the code, hierarchical output, then modify the output statement.

The code is as follows:

import java.util.*;
Public class Main10
Public, static, void, main (String[], args)
Int[] pre = {1,2,4,7,3,5,6,8};
Int[] in = {4,7,2,1,5,3,8,6};
Solve (pre, in);
Public, static, void, solve (int, []pre, int, []in) //pre are preorder traversal, and in is ordered traversal
If (pre.length<1) / / no element is returned
Else if (pre.length==1) / / only one element
System.out.println (pre[0]); / / the output element
/ / find the current root node location in the sequence
Int index = 0;
For (int i=0; i{
If (pre[0]==in[i])
Index = i;
/ / the left half of the first order
Int [] = new int[index] leftPre;
System.arraycopy (pre, 1, leftPre, 0, index);
The right part of the pre order / /
Int len = pre.length-index-1;
Int [] = new int[len] rightPre;
System.arraycopy (pre, index+1, rightPre, 0, len);
In order to / / the left part
Int [] = new int[index] leftIn;
System.arraycopy (in, 0, leftIn, 0, index);
/ / the left half of the order
Int rlen = in.length-index-1;
Int [] = new int[rlen] rightIn;
System.arraycopy (in, index+1, rightIn, 0, rlen);
For left and right subtree recursively / /
Solve (leftPre, leftIn);
Solve (rightPre, rightIn);
System.out.println (pre[0]); / / output
Class TreeNode / / tree node class
Int data;
TreeNode leftNode;
TreeNode rightNode;
Public TreeNode (int data)
This.data = data;

there may be other good method, also look at Lin.

my experience is for reference only.