Title Description
Before entering a binary preorder traversal order and results, rebuild the binary tree.
Sample
给定:
前序遍历是:[3, 9, 20, 15, 7]
中序遍历是:[9, 3, 15, 20, 7]
返回:[3, 9, 20, null, null, 15, 7, null, null, null, null]
返回的二叉树如下所示:
3
/ \
9 20
/ \
15 7
solution
In sequence preorder traversal of the binary tree, the first digit value is always the root node .
In order traversal sequence, the value in the middle of the sequence of the root node , the node located in the left subtree of the root of the left and the right subtree of the node on the right side root value.
Traversal sequences in order to find the root, recursively build the left subtree and the right subtree.
Seen from the figure, the sequence preorder traversal of a number 3 is the value of the root node. Scan order traversal sequence, can determine the position of the root node .
The characteristics of traversal sequence in front of the value of the root node 3 has a number is the value of the left subtree nodes, are located behind the digital values of 3 right subtree node.
Similarly for the same operation for each subtree, recursive
package demo; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.Stack; import java.util.Comparator; public class Solution { class TreeNode{ int val; TreeNode left; TreeNode right; TreeNode(int x){ val = x; } } public TreeNode buildTree(int[] preorder, int[] inorder){ if (preorder == null || inorder == null || preorder.length == 0 || preorder.length != inorder.length) { return null; } return build(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1); } private TreeNode build(int[] preorder, int startPre, int endPre, int[] inorder, int startIn, int endIn ){ if(startPre>endPre || startIn>endIn) return null; TreeNode root = new TreeNode(preorder[startPre]); //树根结点 for(int i=startIn; i<=endIn; i++){ if(inorder[i] == preorder[startPre]){ //注意边界:i-startIn为偏移量 root.left = build(preorder, startPre+1, startPre+i-startIn, inorder, startIn, i-1); root.right = build(preorder, i-startIn+startPre+1, endPre, inorder, i+1, endIn); } } return root; } public static void printPreOrder(TreeNode head) { if (head != null) { System.out.println(head.val); printPreOrder(head.left); printPreOrder(head.right); } } public static void main(String[] args) { int[] preorder = {1,2,4,7,3,5,6,8}; int[] inorder = {4,7,2,1,5,3,8,6}; Solution rt = new Solution(); Solution.TreeNode root = rt.buildTree(preorder, inorder); rt.printPreOrder(root); } }
https://github.com/kexun/jianzhioffer/blob/master/src/com/offer/Day03.java
To be perfect ...