zoukankan      html  css  js  c++  java
  • 654. Maximum Binary Tree最大二叉树

    网址:https://leetcode.com/problems/maximum-binary-tree/

    参考: https://leetcode.com/problems/maximum-binary-tree/discuss/106146/C%2B%2B-O(N)-solution

    我自己的做法是依照题意的逻辑,逐一递归的做法。

    O(n2)

    /**
     * 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* getNode(vector<int>& nums)
        {
            TreeNode* res = new TreeNode(0);
            int maxx = nums[0];
            int maxw = 0;
            // 遍历出最大值和其下标
            for(int i=1; i<nums.size(); i++)
            {
                if(maxx < nums[i])
                {
                    maxx = nums[i];
                    maxw = i;
                }
            }
            res->val = maxx;
            
            // 开始左右节点的构造
            // 最大节点是否位于片段的左端
            if(nums.begin() == nums.begin()+maxw)
            {
                res->left = NULL;
            }
            else
            {   
                // 构造vector片段,继续递归
                vector<int> nums_left(nums.begin(), nums.begin()+maxw);
                res->left = getNode(nums_left);
            }
            // 最大节点是否位于片段的右端
            if(nums.begin()+maxw+1 == nums.end())
            {
                res->right = NULL;
            }
            else
            {
                // 同理
                vector<int> nums_right(nums.begin()+maxw+1, nums.end());
                res->right = getNode(nums_right);
            }
            return res;
        }
        
        TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
            TreeNode* ans = getNode(nums);
            return ans;
        }
    };

    在discuss中发现有O(N)的做法!

  • 相关阅读:
    CentOS8下升级Python3.6到3.9
    web service基础知识
    mysql+centos7+主从复制
    saltstack高效运维
    Docker
    python如何配置virtualenv
    Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy
    nginx+uWSGI+django+virtualenv+supervisor发布web服务器
    RabbitMQ消息队列-Centos7下安装RabbitMQ3.6.1
    flask-wtforms
  • 原文地址:https://www.cnblogs.com/tornado549/p/10778246.html
Copyright © 2011-2022 走看看