LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Question:

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

Note:
You may assume that duplicates do not exist in the tree.

Ideas:

Recursion: the first element of preorder must be the root node.

package treetraversal;public class ConstructBinaryTreeFromPreorderAndInorderTraversal {    public TreeNode buildTree(int[] preorder, int[] inorder) {        return construct(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);    }        private TreeNode construct(int[] preorder, int pstart, int pend, int[] inorder, int istart, int iend) {        if (pstart > pend || istart > iend) return null;        int rootVal = preorder[pstart];        int index = -1;        for (int i = istart; i <= iend; ++i) {            if (inorder[i] == rootVal) {                index = i;                break;            }        }                TreeNode root = new TreeNode(rootVal);                root.left = construct(preorder, pstart + 1, index - istart + pstart, inorder, istart, index - 1);        root.right = construct(preorder, index - istart + pstart + 1, pend, inorder, index + 1, iend);        return root;    }    }

 

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.