• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
THE WAY I AM
博客园    首页    新随笔    联系   管理    订阅  订阅
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)的做法!

posted on 2019-04-27 11:54  549  阅读(83)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3