topic:
And enter the result in a preorder traversal of a binary tree in preorder traversal of the binary tree is reconstructed requested. Suppose Results preorder traversal of the input sequence and are free of duplicate numbers.
E.g:
Preorder traversal sequence {1,2,4,7,3,5,6,8}
Inorder traversal sequence {4,7,2,1,5,3,8,6}
And outputs the reconstructed binary its head node
Ideas:
1. The first node traversed by the root is a known preamble, whereby the preorder divided into two parts, the left part of the left subtree of the root node {4,7,2} (inOrder), the right part of the right subtree of the root node {5,3,8,6} (inOrder)
2. ago by {4,7,2} (inOrder) and Comparative know preorder traversal order traversal is {2,4,7} (preOrder)
2 can be seen to the left subtree of the first stage "root", which is a left subtree {4,7} (inOrder), which is empty right subtree, which traverse the preamble is {4,7} (preOrder)
4 can be seen to the left of the second stage of the sub-tree "root", which is left empty subtree, right subtree is {7}
This, the left sub-tree traversal is complete, right subtree empathy
3. The above ideas recursion
Code
public class Third { class TreeNode{ int val; TreeNode left; TreeNode right; public TreeNode(int val){ this.val = val; } } public void reConstructBST(int[] pre, int[] in){ reBuildBST(pre, 0, pre.length - 1, in, 0, in.length - 1); } private TreeNode reBuildBST(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd){ if(preStart > preEnd || inStart > inEnd){ return null; } TreeNode root = new TreeNode(pre[preStart]); for(int i = 0; i < inEnd; i ++){ if(in[i] == pre[preStart]){ root.left = reBuildBST(pre, preStart, preStart + i - inStart, in, inStart, i - 1); root.right = reBuildBST(pre, preStart + i - inStart + 1, preEnd, in, i + 1, inEnd); } } return root; } }