码迷,mamicode.com
首页 > 其他好文 > 详细

654. Maximum Binary Tree最大二叉树

时间:2019-04-27 13:13:15      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:参考   自己的   ++   自己   nod   二叉树   nbsp   i++   题意   

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

654. Maximum Binary Tree最大二叉树

标签:参考   自己的   ++   自己   nod   二叉树   nbsp   i++   题意   

原文地址:https://www.cnblogs.com/tornado549/p/10778246.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!