求二叉树的高度 递归&非递归实现
2024-09-07 13:32:10
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) { // 递归
// if (null == root) {
// return 0;
// }
// if (null == root.left && null == root.right) {
// return 1;
// }
// if (maxDepth(root.left) >= maxDepth(root.right)) {
// return 1 + maxDepth(root.left);
// } else {
// return 1 + maxDepth(root.right);
// }
// 非递归
if (null == root) {
return 0;
}
if (null == root.left && null == root.right) {
return 1;
}
int depth = 0;
Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root); while (queue.size()>0){
int index = queue.size();
depth++;
for (int i=0;i<index;i++){
TreeNode node = queue.remove();
if (null != node.left || null != node.right){
if (null != node.left){
queue.add(node.left);
}
if (null != node.right){
queue.add(node.right);
}
}
}
}
return depth;
}
}
最新文章
- Tomcat常见问题汇总
- # mysql -u root -p -bash: mysql: command not found
- delphi中Message消息的使用方法
- POI设置边框
- [vijos P1512] SuperBrother打鼹鼠
- Java存储密码用字符数组
- HTTP使用BASIC认证的原理及实现方法
- Unit testing Cmockery 简单使用
- Ext入门学习系列(二)弹出窗体
- Android 混淆proguard的实现(图文)
- app集成微信支付服务端代码-php版本
- 手机端rem如何适配_rem详解及使用方法
- unigui+fastreport报表打印
- Windows桌面或服务器环境下嵌入JavaScript支持(JSRT)
- 三种不同类型的ssh隧道
- rem与px之间的换算(移动端)
- 2017-2018-2 20155234『网络对抗技术』Exp5:MSF基础应用
- Win7/Win8/IIS7/IIS8配置ASP/ACCESS
- HDU 1116 Play on Words(并查集和欧拉回路)(有向图的欧拉回路)
- POJ2676 – Sudoku(数独)—DFS
热门文章
- 最全的 API 接口集合
- 解决Macbook Pro 2017安装Windows10双系统后在Windows系统中Apple蓝牙鼠标不能使用问题
- thinkphp5 不使用form,用input+ajax异步上传图片
- 2019-2020-1 20199308《Linux内核原理与分析》第二周作业
- Shutdown SpringBoot App
- Linux / mac OS Shell常用命令
- vue+elementUI实现权限的部门管理
- Bind+DLZ+MySQL智能DNS的正向解析和反向解析实现方法
- CodeForces 1058C C. Vasya and Golden Ticket
- 数据结构--链式栈--C++实现