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.

Analyse:we can see from the pic above so the left of the pivot element of preorder sequence in inorder sequence is the The left subtree of this element, and the right part are the right subtree of this element.

Runtime:64ms.

Recursion
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8  * };9  */Ten classSolution { One  Public: Atreenode* Buildtree (vector<int>& Preorder, vector<int>&inorder) { -         if(preorder.size () = =0)returnNULL; -         returnBuild (Preorder,0, Preorder.size ()-1, Inorder,0, Inorder.size ()-1); the     } -treenode* Build (vector<int>& Preorder,intPreleft,intPreright, vector<int>& Inorder,intInleft,intinright) { -         if(Preleft > Preright)returnNULL;//When would this case appear -          +treenode* root =NewTreeNode (Preorder[preleft]); -         if(Preleft = = preright)returnRoot; +          A         //find the position of root (Preorder[preleft]) in inorder sequence at         intindex =0; -          for(; index < inorder.size (); index++){ -             if(Inorder[inleft + index] = = Preorder[preleft]) Break; -         } -          -Root->left = Build (preorder, Preleft +1, Preleft + index, inorder, inleft, Inleft + index-1); inRoot->right = Build (preorder, Preleft + index +1, Preright, inorder, Inleft + index +1, inright); -          to         returnRoot; +     } -};

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.