zoukankan      html  css  js  c++  java
  • [Leetcode]654.Maximum Binary Tree

    链接:LeetCode654

    给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:

    二叉树的根是数组中的最大元素。
    左子树是通过数组中最大值左边部分构造出的最大二叉树。
    右子树是通过数组中最大值右边部分构造出的最大二叉树。
    通过给定的数组构建最大二叉树,并且输出这个树的根节点。

    相关标签:递归

    对于构造二叉树相关的题目,先考虑递归算法。这里,我们要将最大元素作为根,并将在左边,右边部分的数组分别进行递归即可。
    代码如下:

    python:

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    
    class Solution:
        def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
            if not nums:
                return
            mx = max(nums)
            mx_ind = nums.index(mx)
            root = TreeNode(mx)
            root.left,root.right = self.constructMaximumBinaryTree(nums[:mx_ind]),self.constructMaximumBinaryTree(nums[mx_ind+1:])
            return root
    

    C++:

    class Solution {
    public:
        TreeNode* fun(vector<int> &nums,int l,int r,int n)
        {
            if(l>r || l<0 || r>=n)
                return NULL;
            int index=l;
            int maxi=INT_MIN;
            for(int i=l;i<=r;i++)
            {
                if(maxi<nums[i])
                {
                    maxi=nums[i];
                    index=i;
                }
            }
            TreeNode *root=new TreeNode(nums[index]);
            root->left=fun(nums,l,index-1,n);
            root->right=fun(nums,index+1,r,n);
            return root;
        }
        TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
            if(nums.size()==0)
                return NULL;
            return fun(nums,0,nums.size()-1,nums.size());
        }
    };
    
  • 相关阅读:
    Go语言如何判断是否是零值
    世界、中国大事记(古代时间线)
    微服务架构带来的分布式单体
    golang如何优雅的编写事务代码
    项目管理的一些知识
    高并发葵花宝典
    深度学习-常见神经网络
    教你用Cobra开发类似docker的命令行
    深度学习是什么
    人工神经网络是什么
  • 原文地址:https://www.cnblogs.com/hellojamest/p/12243162.html
Copyright © 2011-2022 走看看