Construct Binary Tree from Preorder and Inorder Traversal

Source: Internet
Author: User

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.

Method
Construct a tree based on the middle-order traversal and pre-order traversal of the tree and use recursive thinking.
TreeNode getTree (int [] preorder, int preStart, int preEnd, int [] inorder, int inStart, int inEnd) {if (preStart> = preEnd) {return null ;} int cur = preorder [preStart]; TreeNode root = new TreeNode (cur); int I = 0; int j = inStart; while (inorder [j]! = Cur) {j ++; I ++;} root. left = getTree (preorder, preStart + 1, preStart + I + 1, inorder, inStart, inStart + I); root. right = getTree (preorder, preStart + I + 1, preEnd, inorder, inStart + I + 1, inEnd); return root;} public TreeNode buildTree (int [] preorder, int [] inorder) {if (preorder = null) {return null;} int len = preorder. length; return getTree (preorder, 0, len, inorder, 0, len );}


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.