[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:
You may assume that duplicates do not exist in the tree.

Https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

 

Idea: similar to the above question, start with preorder to find the root node and then distinguish the left and right subtree in the middle order.

Because Java does not support returning the addresses of elements behind the array, it is not as elegant as C/C ++. You need to pass a range or copy the array locally.

public class Solution {    public TreeNode buildTree(int[] preorder, int[] inorder) {        if (inorder.length == 0 || preorder.length == 0)            return null;        TreeNode res = build(preorder, 0, preorder.length, inorder, 0, inorder.length);        return res;    }    private TreeNode build(int[] pre, int a, int b, int[] in, int c, int d) {        if (b - a <= 0)            return null;        TreeNode root = new TreeNode(pre[a]);        int idx = -1;        for (int i = c; i < d; i++) {            if (in[i] == pre[a])                idx = i;        }        // use the len, not idx        int len = idx - c;        root.left = build(pre, a + 1, a + 1 + len, in, c, c + len);        root.right = build(pre, a + 1 + len, b, in, c + 1 + len, d);        return root;    }    public static void main(String[] args) {        new Solution().buildTree(new int[] { 3, 9, 20, 15, 7 }, new int[] { 9, 3, 15, 20, 7 });    }}
View code

 

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.