654. Maximum Binary Tree(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/84069992

题目:

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实现明显比递归速度更快。

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/84069992
今日推荐