Given Preorder and inorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Idea: First, according to the pre-order traversal to get the root node, and then in the middle sequence traversal to get the root node position, the left is the left dial hand tree, the right is the right sub-tree.
Then, the structure of the right subtree of Saozi can be solved recursively. The code is as follows:
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public TreeNode buildtree (int[] preorder, int[] inorder) {/** * 1. Based on the pre-order traversal, first determine Root node * 2. Then find the root node in the middle sequence traversal, and determine the location of the root node in the middle order traversal * 3. Segmentation of the left and right subtree based on the index location * 4. Recursive solution to the left and right subtree of the root node */I F (preorder.length = = 0 | | inorder.length = = 0) return null; TreeNode root = new TreeNode (preorder[0]); int k = 0; for (; k < inorder.length; k++) {if (inorder[k] = = Preorder[0]) {break; }} int[] P1 = Arrays.copyofrange (preorder,1,k+1); int[] q1 = arrays.copyofrange (preorder,k+1,preorder.length); int[] P2 = arrays.copyofrange (inorder,0,k); int[] q2 = Arrays.copyofrange (inorder,k+1,inorder.length); Root.left = Buildtree (P1,P2); Root.right = Buildtree (Q1,Q2); return root; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 105.Construct binary tree from preorder and inorder traversal (based on pre-sequence traversal and middle-order traversal constructs two-fork trees)