首页 技术 正文
技术 2022年11月9日
0 收藏 642 点赞 3,131 浏览 1404 个字

Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

比较左子树和右子树的深度,取小的那个返回上来,并+1。

需要注意的是如果没有左子树或右子树。那么无条件取存在的那一边子树深度,并+1.

如果左子树和右子树都没有,那么就是叶子节点,返回深度1.

如果root自身为null,返回0

 public int minDepth(TreeNode root) {
if(root==null)
return 0;
if(root.left==null && root.right==null)
return 1;
if(root.right==null)
return minDepth(root.left)+1;
if(root.left==null)
return minDepth(root.right)+1;
return Math.min(minDepth(root.right),minDepth(root.left))+1;
}

Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

新定义一个函数,表示树的高度,如果是平衡树的话。不是平衡树则置高度为-1. 运用分治法递归,最后得到结果为-1则不是平衡的。基本情况,root==null则高度为0

     public boolean isBalanced(TreeNode root) {
if(height(root)==-1)
return false;
return true;
}
public int height(TreeNode root)
{
if(root==null)
return 0;
int left = height(root.left);
int right = height(root.right);
if(left==-1 || right==-1)
return -1;
if(Math.abs(left-right)>1)
return -1;
return Math.max(left,right)+1;
}

Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

求最大深度方法也是一样,更简单了:

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