Given Preorder and inorder traversal of a tree, construct the binary tree.
Given In-order [1,2,3]
and pre-order [2,1,3]
, return a tree:
2 / 1 3
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/** *@parampreorder:a List of integers that preorder traversal of A tree *@paraminorder:a List of integers that inorder traversal of A tree *@return: Root of a tree*/ PublicTreeNode Buildtree (int[] Preorder,int[] inorder) { //Write your code here if(Preorder = =NULL|| Preorder.length = = 0) return NULL; intSize =preorder.length; TreeNode Root= Build (preorder, 0, size-1, inorder, 0, size-1); returnRoot; } PublicTreeNode Build (int[] Preorder,intPre_start,intPre_end,int[] inorder,intIn_start,intin_end) { if(Pre_start > Pre_end | | in_start >in_end)return NULL; TreeNode Root=NewTreeNode (Preorder[pre_start]); intK =In_start; for(; k <= In_end; k++){ if(Inorder[k] = =Preorder[pre_start]) Break; } TreeNode Left= Build (preorder, Pre_start + 1, Pre_start + K-in_start, inorder, In_start, k-1); TreeNode Right= Build (preorder, Pre_start + K-in_start + 1, pre_end, inorder, K + 1, In_end); Root.left=Left ; Root.right=Right ; returnRoot; } }
Lintcode-medium-construct Binary Tree from preorder and inorder traversal