Lintcode-medium-construct Binary Tree from preorder and inorder traversal

Source: Internet
Author: User
Tags lintcode

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.