1 Public classReconstructbinarytree {2 Public Static voidMain (string[] args) {3 NewReconstructbinarytree (). Reconstructbinarytree (New int[] {1, 2, 4,47, 3, 5, 6, 8},New int[] {4, 7, 2, 1, 5, 3, 8, 6 });5 }6 7 PublicTreeNode Reconstructbinarytree (int[] Pre,int[] in) {8 returnReconstructbinarytree (pre, 0, Pre.length-1, in, 0,9In.length-1);Ten } One A PublicTreeNode Reconstructbinarytree (int[] Pre,intStartpre,intEndpre, - int[] in,intStartin,intEndin) { - the if(Startpre > Endpre | | startin >Endin) - return NULL; - -TreeNode root =NewTreeNode (Pre[startpre]);//Constructing Roots + for(inti = Startin; I <= Endin; i++) { - //finding roots in the middle sequence traversal + if(In[i] = =Pre[startpre]) { A atRoot.left = Reconstructbinarytree (pre, Startpre + 1, I --Startin + Startpre, in, Startin, i-1); -Root.right = Reconstructbinarytree (pre, I-startin +Startpre -+ 1, Endpre, in, i + 1, Endin); - Break; - } in } - to returnRoot; + } - } the * classTreeNode { $ intVal;Panax Notoginseng TreeNode left; - TreeNode right; the +TreeNode (intx) { Aval =x; the } +}
Pre-sequence traversal: 12473568
Middle Sequence Traversal: 47215386
Refactoring process: 1. The first value in a pre-order traversal is the root
2. The location of the root in the middle sequence traversal, the left side is the Zuozi of the middle order traversal result (472), right is the right subtree of the middle sequence traversal results (5386)
3. In the pre-sequence traversal, the pre-order traversal result of the Zuozi is (247), and the first-order traversal result of the right subtree is (3568)
4.2 is the root of the Zuozi, and 3 is the root of the right subtree, repeating the above operation
Reconstructing binary tree based on pre-order and middle sequence traversal