Leetcode Construct Binary Tree from preorder and inorder traversal

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.

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

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.