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)的做法!

  • 相关阅读:
    27. Remove Element
    26. Remove Duplicates from Sorted Array
    643. Maximum Average Subarray I
    674. Longest Continuous Increasing Subsequence
    1. Two Sum
    217. Contains Duplicate
    448. Find All Numbers Disappeared in an Array
    566. Reshape the Matrix
    628. Maximum Product of Three Numbers
    UVa 1349 Optimal Bus Route Design (最佳完美匹配)
  • 原文地址:https://www.cnblogs.com/tornado549/p/10778246.html
Copyright © 2011-2022 走看看