今日题目:
104.二叉树的最大深度
111.二叉树的最小深度
222.完全二叉树的节点个数
今日总结
没啥说的。之后重新做做第三题。
104. 二叉树的大深度
要点
- 没啥说的
代码:
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
return max(maxDepth(root.Left), maxDepth(root.Right))+1
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
111.二叉树的最小深度
要点:
- 有坑!不同于最大深度,这题主要是当根节点没有左子树或者右子树时,其最小深度并不是1,而是另一个子树的最小深度。
- 类似于昨天的对称二叉树,这里要分开处理左右节点
func minDepth(root *TreeNode) int {
if root == nil {
return 0
}
leftDepth := minDepth(root.Left)
rightDepth := minDepth(root.Right)
if root.Left == nil && root.Right != nil {
return rightDepth + 1
}
if root.Right == nil && root.Left != nil {
return leftDepth + 1
}
return min(leftDepth,rightDepth)+1
}
func min(a int, b int) int {
if a < b {
return a
}
return b
}
222.完全二叉树的节点个数
要点:
- 偷懒了。下次研究怎么利用完全二叉树的性质。
func countNodes(root *TreeNode) int {
if root == nil {
return 0
}
return countNodes(root.Left)+countNodes(root.Right)+1
}