Given Preorder and inorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Test instructions: Two forks the tree before, the middle order constructs two crosses the tree.
Idea: the classic topic.
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution { TreeNode build (int[] preorder, int[] inorder, int l, int r, int len) {TreeNode root = null; if (Len < 1) return root;root = new TreeNode (preorder[l]), int index = 0;for (int i = 0; i < len; i++) if (inorder[r+ I] = = Preorder[l]) {index = I;break;} Root.left = Build (Preorder, Inorder, l+1, R, index); root.right = Build (Preorder, inorder, L+1+index, R+1+index, Len-1-inde x); return root;} Public TreeNode Buildtree (int[] preorder, int[] inorder) { int n = preorder.length; Return build (preorder, inorder, 0, 0, n);} }
Leetcode Construct Binary Tree from preorder and inorder traversal