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

猜你喜欢

转载自www.cnblogs.com/tornado549/p/10778246.html