当前位置: 首页 > news >正文

力扣654. 最大二叉树

Problem: 654. 最大二叉树

文章目录

  • 题目描述
  • 思路
  • 复杂度
  • Code

题目描述

在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

思路

对于构造二叉树这类问题一般都是利用先、中、后序遍历,再将原始问题分解得出结果

1.定义递归函数build,每次将一个数组中的最大值作为当前子树的根节点构造二叉树;
2.每次找取当前范围内的最大值,作为当前的根节点;
3.递归求取出其左子树与右子树

复杂度

时间复杂度:

O ( n 2 ) O(n^2) O(n2);其中n为二叉树节点的个数

空间复杂度:

O ( n ) O(n) O(n)

Code

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
class Solution {/*** Maximum Binary Tree** @param nums Given array* @return TreeNode*/public TreeNode constructMaximumBinaryTree(int[] nums) {return build(nums, 0, nums.length - 1);}/*** Construction of binary tree function implementation** @param nums Given array* @param low  Given the left endpoint of the array* @param high Given the right endpoint of the array* @return TreeNode*/TreeNode build(int[] nums, int low, int high) {if (low > high) {return null;}int index = -1;int maxVal = Integer.MIN_VALUE;for (int i = low; i <= high; ++i) {if (maxVal < nums[i]) {maxVal = nums[i];index = i;}}//The root node is constructed first,// and then the left and right subtrees are constructedTreeNode root = new TreeNode(maxVal);root.left = build(nums, low, index - 1);root.right = build(nums, index + 1, high);return root;}
}
http://www.lryc.cn/news/356030.html

相关文章:

  • 基于Netty实现WebSocket客户端
  • homebrew安装mysql的一些问题
  • 产线问题排查
  • 华为WLAN实验继续-2,多个AP如何部署
  • 手把手教你写Java项目(1)——流程
  • 微信小程序post请求
  • frm一级4个1大神复习经验分享系列(二)
  • 理解磁盘分区与管理:U启、PE、DiskGenius、MBR与GUID
  • GPT-4o和GPT-4有什么区别?我们还需要付费开通GPT-4?
  • 《C++ Primer Plus》第十二章复习题和编程练习
  • 2024 年科技裁员综合清单
  • Linux系统编程学习笔记
  • vue3 excel 文件导出
  • 优雅的代码规范
  • JVM、JRE 和 JDK 的区别,及如何解决学习中可能会遇到的问题
  • 【开源】加油站管理系统 JAVA+Vue.js+SpringBoot+MySQL
  • 详解 Scala 的泛型
  • 【本周面试问题总结】
  • SaltStack
  • 【Rust日报】Rust 中的形式验证
  • vue3项目中新增修改时使用nextTick时遇到的问题
  • 算法训练 | 二叉树Part7 | 530.二叉搜索树的最小绝对差、501.二叉搜索树中的众数
  • C++面向对象程序设计 - 标准输出流
  • 警惕Mallox勒索病毒的最新变种hmallox,您需要知道的预防和恢复方法。
  • 2024年华为OD机试真题-火星文计算-C++-OD统一考试(C卷D卷)
  • 3.00001 postgres如何初始化系统参数?
  • C# 读取 CSV 文件的方法汇总
  • element+ 引入图标报错 Failed to resolve import “@element-plus/icons-vue“ from “
  • Github 2024-05-25 开源项目日报 Top10
  • VPN的详细理解