LeetCode:104.二叉树的最大深度
问题描述
解决方案:
1.思路
如果我们知道了左子树和右子树的最大深度
l
l
l 和
r
r
r ,那么该二叉树的最大深度即为
m
a
x
(
l
,
r
)
+
1
max(l,r)+1
ma x ( l , r ) + 1 ; 而左子树和右子树的最大深度又可以以同样的方式进行计算。因此我们可以用「深度优先搜索」的方法来计算二叉树的最大深度。 递归在访问到空节点时退出。
2.代码实现
class Solution {
public int maxDepth ( TreeNode root) {
if ( root == null ) {
return 0 ;
} else {
int leftHeight = maxDepth ( root. left) ;
int rightHeight = maxDepth ( root. right) ;
return Math . max ( leftHeight, rightHeight) + 1 ;
}
}
}
3.复杂度分析
LeetCode_559:n叉树的最大深度
问题描述
解决方案:
1.思路:
如果根节点有
N
N
N 个子节点,则这
N
N
N 个子节点对应
N
N
N 个子树。记
N
N
N 个子树的最大深度中的最大值为
m
a
x
C
h
i
l
d
D
e
p
t
h
maxChildDepth
ma x C hi l d De pt h ,则该 NNN 叉树的最大深度为
m
a
x
C
h
i
l
d
D
e
p
t
h
+
1
maxChildDepth+1
ma x C hi l d De pt h + 1 。 每个子树的最大深度又可以以同样的方式进行计算,递归在访问到空节点时退出。
2.代码实现
class Solution {
public int maxDepth ( Node root) {
if ( root == null ) {
return 0 ;
}
int maxChildDepth = 0 ;
List < Node > children = root. children;
for ( Node child : children) {
int childDepth = maxDepth ( child) ;
maxChildDepth = Math . max ( maxChildDepth, childDepth) ;
}
return maxChildDepth + 1 ;
}
}
3.复杂度分析
LeetCode_111.二叉树的最小深度
解决方案:
1.思路:
使用深度优先搜索的方法,遍历整棵树,记录最小深度。 对于每一个非叶子节点,我们只需要分别计算其左右子树的最小叶子节点深度。
class Solution {
public int minDepth ( TreeNode root) {
if ( root == null ) {
return 0 ;
}
if ( root. left == null && root. right == null ) {
return 1 ;
}
int min_depth = Integer . MAX_VALUE ;
if ( root. left != null ) {
min_depth = Math . min ( minDepth ( root. left) , min_depth) ;
}
if ( root. right != null ) {
min_depth = Math . min ( minDepth ( root. right) , min_depth) ;
}
return min_depth + 1 ;
}
}
3.复杂度分析
LeetCode_222.完全二叉树的节点个数
解决方案:
1.思路:
如果整个树不是满二叉树,就递归其左右孩子,直到遇到满二叉树为止,用公式计算这个子树(满二叉树)的节点数量: 这里关键在于如何去判断一个左子树或者右子树是不是满二叉树呢? 在完全二叉树中,如果递归向左遍历的深度等于递归向右遍历的深度,那说明就是满二叉树。
2.代码实现
class Solution {
public int countNodes ( TreeNode root) {
if ( root == null ) return 0 ;
TreeNode left = root. left;
TreeNode right = root. right;
int leftDepth = 0 , rightDepth = 0 ;
while ( left != null ) {
left = left. left;
leftDepth++ ;
}
while ( right != null ) {
right = right. right;
rightDepth++ ;
}
if ( leftDepth == rightDepth) {
return ( 2 << leftDepth) - 1 ;
}
return countNodes ( root. left) + countNodes ( root. right) + 1 ;
}
}
3.复杂度分析
时间复杂度:
O
(
l
o
g
n
∗
l
o
g
n
)
O(log n * log n)
O ( l o g n ∗ l o g n ) 空间复杂度:
O
(
l
o
g
n
)
O(log n)
O ( l o g n )