当前位置:网站首页>LeetCode-543-二叉树的直径
LeetCode-543-二叉树的直径
2022-06-21 20:36:00 【z754916067】
题目

思路
- 感觉这个不会用递归做…果然是太久没写题了,简单题都没思路了。
- 找出把每一个节点作为根节点的直径长度然后求最大值?确实是这个思路,通过了。
代码
int ans=Integer.MIN_VALUE;
public int diameterOfBinaryTree(TreeNode root) {
if(root.left==null && root.right==null) return 0;
//无意义 占位符号
int flag=DFS(root);
return ans;
}
public int DFS(TreeNode root){
//把当前节点作为根节点 如果走到叶子节点了 说明以当前节点为根节点的直径为0 但将其作为一边 则返回1
if(root.left==null && root.right==null) return 1;
//否则计算
int leftval=0,rightval=0;
if(root.left!=null) leftval = DFS(root.left);
if(root.right!=null) rightval = DFS(root.right);
if(leftval+rightval>ans) {
ans=leftval+rightval;
}
//同理返回两边中的最大值+1
return Math.max(leftval,rightval)+1;
}
边栏推荐
- 从-1开始实现一个中间件
- 【深入理解TcaplusDB技术】 Tmonitor模块架构
- 【深入理解TcaplusDB技术】单据受理之事务执行
- 2022 Foshan Tanzhou ceramics exhibition held a press conference to launch ten key points of the exhibition
- Using streamapi assertion combination and local cache for fuzzy query (nearly 1000 times more efficient than MySQL)
- Zhengweimin, academician of the Chinese Academy of Engineering: I am optimistic that China will have a place in the next it Era
- Shell script simple syntax
- 弗吉尼亚大学:Ingy ElSayed-Aly | 多智能体强化学习中的基于逻辑的奖励形成
- 分别利用for、while、do while,循环求1-100的和
- [deeply understand tcapulusdb technology] table management of document acceptance
猜你喜欢

An Chaoyun was selected as one of the "top ten cloud computing solution providers" in the Asia Pacific region by cioreview in 2022

【LeetCode】8、字符串转换整数(atoi)

British teddy bear joins the pubg mobile game

HIC Pro | HIC data processing tool

Nacos安装指南

InstaDeep Ltd:Arthur Flajolet | 单机上基于群体的快速强化学习

刷题笔记(十六)--二叉树:修改与构造

【深入理解TcaplusDB技术】TcaplusDB构造数据

秒懂微服务

Implement a middleware from -1
随机推荐
从-1开始实现一个中间件
Implement a middleware from -1
Notes on question brushing (17) -- binary search tree: about attribute problems
Notes on topic brushing (16) -- binary tree: modification and construction
Worthington deoxyribonuclease I solution
Nacos安装指南
Leetcode question brushing: SF Technology Smart logistics Campus Technology Challenge
File i/o
[deeply understand tcapulusdb technology] tcapulusdb import data
HIC Pro | HIC data processing tool
MitoZ|Multi-Kmer mode
如何卸载用conda命令安装的包
Lifting method (I) AdaBoost
class path resource [classpath*:mapper/*.xml] cannot be opened because it does not exist
Pi4j GPIO pin pull-up resistance, pull-down resistance concept
[in depth understanding of tcapulusdb technology] tcapulusdb business data backup
An Chaoyun was selected as one of the "top ten cloud computing solution providers" in the Asia Pacific region by cioreview in 2022
Specificity and application of Worthington Papain
GDB debugging skills (0) getting started with GDB
Use the for loop to calculate n! Value of