654. Maximum Binary Tree(python+cpp)

题目:

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

解释:
dfs,或者用栈实现都行。
dfs的写法较简单,python代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if not nums:
            return None
        _max=max(nums)
        root=TreeNode(_max)
        _index=nums.index(_max)
        left=nums[:_index]
        right=nums[_index+1:]
        if left:
            root.left=self.constructMaximumBinaryTree(left)
        if right:
            root.right=self.constructMaximumBinaryTree(right)
        return root    

c++代码:

/**
 * 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* constructMaximumBinaryTree(vector<int>& nums) {
        if (nums.size()==0)
            return NULL;
        vector<int>::iterator maxp=max_element(nums.begin(),nums.end());
        int max_val=*maxp;
        TreeNode* root=new TreeNode(max_val);
        vector<int>left(nums.begin(),maxp);
        vector<int>right(maxp+1,nums.end());
        if (left.size()>0)
            root->left=constructMaximumBinaryTree(left);
        if(right.size()>0)
            root->right=constructMaximumBinaryTree(right);
        return root;
    }
};

stack实现,略难理解,python代码 :

class Solution:
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        stack=[]
        for num in nums:
            cur=TreeNode(num)
            #把在当前结点左边且小于它的都变成其左子树
            while stack and num>stack[-1].val:
                cur.left=stack.pop()
            #当前结点变成在它左边且大于它的结点的右子树
            if stack:
                stack[-1].right=cur
            stack.append(cur)
        return stack[0]

c++代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include<stack>
using namespace std;
class Solution {
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        stack<TreeNode*> _stack;
        for (auto num:nums)
        {
            TreeNode* cur=new TreeNode(num);
            while(!_stack.empty() && num>_stack.top()->val)
            {
                 cur->left=_stack.top();
                _stack.pop();
                
            }
               
    
            if(!_stack.empty())
                _stack.top()->right=cur;
            _stack.push(cur);
        }
        TreeNode* tmp=NULL;
        while(!_stack.empty())
        {
            tmp=_stack.top();
            _stack.pop();
        }
        return tmp;
    }
};

总结:
用stack实现明显比递归速度更快。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值