[Leetcode] 105. Construct binary tree from preorder and inorder traversal by first order and mid-order traversal build two forks

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.

For example, given

preorder = [3,9,20,15,7]inorder = [9,3,15,20,7]

Return the following binary tree:

    3   /   9    /   7

A binary tree is constructed by traversing the first and middle sequence of a tree.

Java:

Public TreeNode Buildtree (int[] preorder, int[] inorder) {    return helper (0, 0, inorder.length-1, preorder, inorder); }public TreeNode Helper (int prestart, int instart, int inend, int[] preorder, int[] inorder) {    if (Prestart > Preor der.length-1 | | Instart > Inend) {        return null;    }    TreeNode root = new TreeNode (Preorder[prestart]);    int inindex = 0; Index of current root in inorder for    (int i = Instart; I <= inend; i++) {        if (inorder[i] = = root.val) {            Inindex = i;        }    }    Root.left = Helper (Prestart + 1, Instart, inIndex-1, preorder, inorder);    Root.right = Helper (Prestart + Inindex-instart + 1, Inindex + 1, inend, preorder, inorder);    return root;}

Python:recursive

def buildtree (self, Preorder, inorder):    if inorder:        ind = inorder.index (Preorder.pop (0))        root = TreeNode ( Inorder[ind])        root.left = Self.buildtree (preorder, Inorder[0:ind])        root.right = Self.buildtree (Preorder, Inorder[ind+1:])        return root

Python:

Class Treenode:def __init__ (self, x): Self.val = x self.left = None self.right = Noneclass Soluti On: # @param preorder, a list of integers # @param inorder, a list of integers # @return a tree node def build        Tree (self, Preorder, inorder): Lookup = {} for I, Num in enumerate (inorder): lookup[num] = i Return Self.buildtreerecu (lookup, preorder, inorder, 0, 0, Len (inorder)) def buildtreerecu (self, lookup, preorder, I Norder, Pre_start, In_start, in_end): if In_start = = In_end:return None node = TreeNode (Preorder        [Pre_start]) i = Lookup[preorder[pre_start]] node.left = SELF.BUILDTREERECU (lookup, preorder, inorder, Pre_start + 1, In_start, i) Node.right = SELF.BUILDTREERECU (lookup, preorder, inorder, Pre_start + 1 + i-in_start, i + 1, in_end) r Eturn Nodeif __name__ = = "__main__": preorder = [1, 2, 3] inorder = [2, 1, 3] result = solution (). Buildtree (Preo Rder, inorder) print (result.val) print (result.left.val) print (result.right.val) 

C + +:

Time:o (n)//Space:o (n)/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}};        */class Solution {public:treenode* Buildtree (vector<int>& preorder, vector<int>& inorder) {        Unordered_map<int, size_t> In_entry_idx_map;        for (size_t i = 0; i < inorder.size (); ++i) {In_entry_idx_map.emplace (inorder[i], i);                                            } return Reconstructpreinordershelper (preorder, 0, Preorder.size (), inorder, 0, Inorder.size (),    IN_ENTRY_IDX_MAP);    }//reconstructs the binary tree from pre[pre_s:pre_e-1] and//in[in_s:in_e-1].                                           TreeNode *reconstructpreinordershelper (const vector<int>& Preorder, size_t pre_s, size_t pre_e,                    Const vector<int>& Inorder, size_t in_s, size_t in_e,                       Const Unordered_map<int, size_t>& in_entry_idx_map) {if (pre_s = = Pre_e | | in_s =        = in_e) {return nullptr;        } Auto idx = in_entry_idx_map.at (preorder[pre_s]);        Auto left_tree_size = idx-in_s;        Auto node = new TreeNode (preorder[pre_s]);                                                  Node->left = Reconstructpreinordershelper (preorder, pre_s + 1, pre_s + 1 + left_tree_size,        Inorder, in_s, IDX, in_entry_idx_map);                                                   Node->right = Reconstructpreinordershelper (preorder, pre_s + 1 + left_tree_size, pre_e,        Inorder, idx + 1, in_e, in_entry_idx_map);    return node; }};

  

Similar topics:

[Leetcode] 106. Construct binary tree from inorder and postorder traversal by the middle sequence and post-order traversal to build two-fork trees

 

[Leetcode] 105. Construct binary tree from preorder and inorder traversal by first order and mid-order traversal build two forks

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.