【leetcode】654. Maximum Binary Tree(Python & C++)

来源:互联网 发布:剑三纯阳捏脸数据成男 编辑:程序博客网 时间:2024/05/17 04:43

654. Maximum Binary Tree

题目链接

654.1 题目描述:

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 is the maximum tree constructed from left part subarray divided by the maximum number.
2、The right subtree is 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 of this tree.

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 will be in the range [1,1000].

654.2 解题思路:

  1. 思路一:采用递归,分为三步,分别为获取指定数组序列的最大值,构建子树,返回根节点。

    • 获取指定数组最大值findmax函数(Python自带max函数):参数为数组nums,起始位置start,终止位置end,最大值max。求出数组中,指定了起始位置和终止位置后的最大值,并返回最大值所在数组的下标index,如果起始位置等于终止位置,返回index=-1。

    • 构建子树getsubtree函数:参数为数组nums,起始位置start,终止位置end。定义最大值max,调用findmax函数,定义并初始化index为数组nums从0到数组结尾中最大值的下面。如果index为-1,说明此时搜寻的数组为空,则返回null节点。否则,创建val值为max的节点node,递归调用getsubtree函数,得到其左右节点。其左节点为getsubtree(nums, start, index),右节点为getsubtree(nums, index + 1, end),注意nums的起始与终止位置。最后返回node节点。

    • 返回根节点constructMaximumBinaryTree函数:返回调用getsubtree(nums, 0, nums.size())函数的结果。

  2. 思路二:原理上利用栈,写法上可以用vector向量代替stack(Python中可使用list)。定义vector,用来存放节点。遍历nums数组,首先获取当前节点cur,其值为nums[i]。重复判断如果vector不空,并且其最后一个节点的值比当前节点cur小,则cur的左节点即为vector最后一个节点,并且pop出最后一个节点。当这个操作完成后,如果vector仍不为空,说明,其最后一个节点的值比当前节点cur的值要大,则最后一个节点的右节点即为cur。然后将cur节点push进vector。遍历结束后,返回vector第一个节点即为根节点。

  3. 思路三:分为c++和Python。

    • c++:同思路二,不过是将vector换乘了栈stack。

    • Python:类似于思路一,只不过利用Python语言的特性。

654.3 C++代码:

1、思路一代码(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 getsubtree(nums, 0, nums.size());    }};

2、思路二代码(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、思路三代码(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代码:

1、思路一代码(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 node        return getsubtree(nums, 0, len(nums))

2、思路二代码(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、思路三代码(249ms)

class Solution2(object):    def constructMaximumBinaryTree(self, nums):        """        :type 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

原创粉丝点击