Leetcode Construct Binary Tree from preorder and inorder traversal-----java

Source: Internet
Author: User

Given Preorder and inorder traversal of a tree, construct the binary tree.

Note:
Assume that duplicates does not exist in the tree.

Give the pre-order traversal and the middle sequence traversal, and then seek the tree.

It's very regular. Recursion can be achieved.

/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode Buildtree (int[] Preorder,int[] inorder) {        intLen =preorder.length; if(len = = 0)            return NULL; returnHelper (preorder,0,len-1,inorder,0,len-1); }     PublicTreeNode Helper (int[] Preorder,intPre_start,intPre_end,int[] inorder,intIn_start,intin_end) {        if(Pre_start > Pre_end | | in_start >in_end)return NULL; TreeNode node=NewTreeNode (Preorder[pre_start]); intSize = 0;  for(inti = In_start;i<=in_end && inorder[i]! = preorder[pre_start];i++,size++)            ; Node.left= Helper (preorder,pre_start+1,pre_start+size,inorder,in_start,in_start+size-1); Node.right= Helper (preorder,pre_start+size+1,pre_end,inorder,in_start+size+1, In_end); returnnode; }}

Speed is not fast, the fastest answer is also a reference.

It's not how good the algorithm is, but he's

for (int i = In_start;i<=in_end && inorder[i]! = preorder[pre_start];i++,size++)            ;

Here the traversal is chosen from the backward forward, due to the particularity of the test data, resulting in the rapid response.

Leetcode Construct Binary Tree from preorder and inorder traversal-----java

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.