说道二叉树的深度,第一反应就是二叉树的最大深度 , 在 leetcode 上有一道二叉树的最小深度
其实 最大深度 / 最小深度 其实就是根节点到叶子节点的 最大距离 / 最小距离 。
总结起来就是:
d
e
p
t
h
=
{
1
+
M
a
t
h
.
m
a
x
(
l
e
f
t
D
e
p
t
h
,
r
i
g
h
t
D
e
p
t
h
)
最大深度
1
+
M
a
t
h
.
m
i
n
(
l
e
f
t
D
e
p
t
h
,
r
i
g
h
t
D
e
p
t
h
)
最小深度
depth = \begin{cases} 1 + Math.max(leftDepth , rightDepth)& \text{最大深度} \\ 1 + Math.min(leftDepth , rightDepth)& \text{最小深度} \end{cases}
depth={1+Math.max(leftDepth,rightDepth)1+Math.min(leftDepth,rightDepth)最大深度最小深度
树节点表达方式
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
}
二叉树最大深度实现
public class Solution {
/**
* @param root TreeNode类
* @return int整型
*/
public int maxDepth (TreeNode root) {
// write code here
if (root == null) return 0;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return 1 + Math.max(leftDepth,rightDepth);
}
}
二叉树最小深度实现
需要注意的是,如果存在一个某一个子树为空时,不能认为最小深度是 0 ,
注意: 最小深度 是根节点到叶子节点的 最小距离
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
// 当一个左子树为空,右不为空,这时并不是最低点
if(root.left == null && root.right != null)
return 1 + rightDepth;
// 当一个右子树为空,左不为空,这时并不是最低点
if(root.left != null && root.right == null)
return 1 + leftDepth;
return 1 + Math.min(leftDepth , rightDepth);
}
}