首页 技术 正文
技术 2022年11月7日
0 收藏 526 点赞 1,186 浏览 729 个字

算法分析:求树的最小最大深度时候,都有两种方法,第一种是递归思想。树最大最小深度,即为它的子树的最大最小深度+1,是动态规划的思想。还有一种方法是层序遍历树,只不过求最小深度时,找到第一个叶子节点就可以返回,该节点的深度,即为树的最小深度。求最大深度时,需要层序遍历完整棵树。

public class MaximumDepthofBinaryTree
{
public int maxDepth(TreeNode root)
{
if(root == null)
{
return 0;
}
int lmax = maxDepth(root.left);
int rmax = maxDepth(root.right);
if(lmax == 0 && rmax == 0)
{
return 1;
}
if(lmax == 0)
{
return rmax + 1;
}
if(rmax == 0)
{
return lmax + 1;
}
return Math.max(lmax, rmax) + 1;
}public int maxDepth2(TreeNode root)
{
if(root == null)
{
return 0;
}
ArrayList<TreeNode> list = new ArrayList<>();
list.add(root);
int count = 0;
while(!list.isEmpty())
{
ArrayList<TreeNode> temp = new ArrayList<>();
for (TreeNode node : list) {
if(node.left != null)
{
temp.add(node.left);
}
if(node.right != null)
{
temp.add(node.right);
}
}
count ++;
list = temp;
}
return count;
}
}

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,493
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295