"Leetcode" 654. Maximum Binary Tree (Python & C + +)

Source: Internet
Author: User
654. Maximum Binary Tree

Topic link 654.1 topic Description:

Given an integer array with no duplicates. A Maximum tree building on this array is defined as follow:

The root is the maximum number in the array.
1. The left subtree are the maximum tree constructed from left part Subarray divided by the maximum number.
2, the right subtree are the maximum tree constructed from right part subarray divided by the maximum number.
3. Construct the maximum tree by the given array and output the root node.

Example 1:
Input: [3,2,1,6,0,5]
Output:return the tree root node representing the following tree:

  6
/   \
3     5
\    / 
 2  0   
   \
    1

Note:
The size of the given array is in the range [1,1000]. 654.2 Problem Solving ideas:

Idea one: adopt recursion, divide into three steps, get the maximum value of the specified array sequence respectively, build subtree, return root node.

Gets the specified array maximum value Findmax function (Python's own Max function): Arguments are array nums, start position start, terminate position end, Max Max. In the number group, specify the maximum value after the start and end positions, and return the subscript index of the array with the maximum value, and return index=-1 if the starting position equals the ending position.

Build subtree Getsubtree function: Parameter array nums, start position start, terminate position end. Define Max Max, call the Findmax function, and define and initialize the index array nums from 0 to the bottom of the array's maximum value. If index is-1, which indicates that the array being searched for is empty, the null node is returned. Otherwise, create node nodes of Val value Max, recursively call the Getsubtree function and get the left and right nodes. The left node is Getsubtree (Nums, start, index), and the right node is Getsubtree (nums, index + 1, end), noting the starting and ending position of the nums. Finally, the node nodes are returned.

Returns the root node Constructmaximumbinarytree function: Returns the result of calling the Getsubtree (nums, 0, nums.size ()) function.

Idea two: Using the stack in principle, you can use a vector vector instead of stack (the list is available in Python). Defines vectors that are used to store nodes. Traverses the Nums array, first obtains the current node cur, and its value is nums[i]. Repeat judgment if the vector is not empty and the last node's value is smaller than the current node cur, then the left node of cur is the vector's last node, and pops out the last node. When this operation is complete, if the vector is still not empty, the last node's value is larger than the current node cur, then the right node of the last node is cur. Then push the cur node into the vector. After the traversal is completed, the first node of the vector is returned as the root node.

Idea three: Divide into C + + and Python.

C + +: The same idea two, but the vector transfer to stack stacks.

Python: Similar to idea one, just take advantage of the features of the Python language. 654.3 C + + code:

1, thinking One code (76MS):

Class Solution137 {public:int Findmax (vector<int>nums,int start,int end,int &max) {if (start
        = = end) return-1;
        int index = start;
        max = Nums[start]; for (int i = start + 1; i < end;i++) {if (Nums[i]>max) {max = Nums
                [i];
            index = i;
    } return index;
        } treenode* Getsubtree (vector<int>& nums,int start,int end) {int max;
        int index = Findmax (Nums,start,end,max);    
        if (index==-1) return NULL;
            else {TreeNode *tempnode = new TreeNode (max);
            Tempnode->left = Getsubtree (nums, start, index);
            Tempnode->right = Getsubtree (nums, index + 1, end);
        return tempnode; } treenode* Constructmaximumbinarytree (vector<int>& nums) {return GETSUBTR EE (nums, 0, NUMS.SIze ());
 }
};

2, train of Thought two code (62MS)

Class Solution137_1 {public
:
    treenode* constructmaximumbinarytree (vector<int>& nums) {
        vector<treenode*>store;
        for (int i = 0; i < nums.size (); i++)
        {
            TreeNode *cur = new TreeNode (nums[i));
            while (Store.size ()!=0 && store.back ()->val<nums[i])
            {
                cur->left = Store.back ();
                Store.pop_back ();
            }
            if (Store.size ()!=0)
            {
                store.back ()->right = cur;
            }
            Store.push_back (cur);
        }
        return Store.front ();
    }
;

3, thinking Three code (62MS)

Class Solution137_2 {public
:
    treenode* constructmaximumbinarytree (vector<int>& nums) {
        stack <TreeNode*>store;
        for (int i = 0; i < nums.size (); i++)
        {
            TreeNode *cur = new TreeNode (nums[i));
            while (!store.empty () && store.top ()->val < nums[i])
            {
                cur->left = Store.top ();
                Store.pop ();
            }
            if (!store.empty ())
            {
                store.top ()->right = cur;
            }
            Store.push (cur);
        }
        TreeNode *p = NULL;
        while (!store.empty ())
        {
            p = store.top ();
            Store.pop ();
        }
        return p;
    }
;
654.4 Python code:

1, thinking One code (786MS)

Class Solution (object):
    def constructmaximumbinarytree (self, Nums): ""
        : Type Nums:list[int]
        : Rtype:treenode
        "" "
        def Getsubtree (nums,start,end):
            if start==end: Return
                None
            Max_=max (nums[ Start:end])
            Node=treenode (max_)
            node.left=getsubtree (Nums,start,nums.index (max_))
            node.right= Getsubtree (Nums, Nums.index (max_) +1, end) return to
            node return

        getsubtree (nums, 0, Len (nums))

2, train of Thought two code (346MS)

Class Solution1 (object):
    def constructmaximumbinarytree (self, Nums): ""
        : Type Nums:list[int]
        : Rtype:treenode
        "" "
        store=[] for
        i in range (0,len (nums)):
            Cur=treenode (nums[i)) while
            Len (store !=0 and Store[len (store) -1].val<cur.val:
                Cur.left=store[len (Store)-1]
                store.pop ()
            If Len (store) !=0:
                Store[len (store) -1].right=cur
            store.append (cur) return
        store[0]

3, thinking Three code (249MS)

class Solution2 (object): Def constructmaximumbinarytree (self, Nums): "" ": Typ E Nums:list[int]: Rtype:treenode "" If not Nums:return None Node=treenode ( Max (nums)) I=nums.index (Max (nums)) if NUMS[:I]: Node.left=self.constructmaximumbinarytree (nums [: i]) if nums[i+1:]: Node.right=self.constructmaximumbinarytree (nums[i+1:]) return node 
Related Article

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.