给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
题目来源:LeetCode - 111
以下是正常求树高度的递归边界条件:
- 当前节点为空时,返回 0
- 否则返回 max(左子树深度, 右子树深度) + 1
而本题中 **A leaf is a node with no children.** 是重点,因为是最小深度,所以与正常求树深度的递归边界条件不同。
以下是本题最小树高度的递归边界条件:
- 当前节点为空时,返回 0
- 当前节点的左右子节点为空时,返回 1
- 当前节点的左右子节点有且仅有一者不为空时,返回 不为空的子树深度 + 1
- 否则返回 min(左子树深度, 右子树深度) + 1
于是有了以下代码**(优化前)**
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minDepth(root *TreeNode) int {
if root == nil { return 0 }
if root.Left == nil && root.Right == nil{
return 1
}
if root.Left != nil && root.Right == nil{
return minDepth(root.Left) + 1
}
if root.Right != nil && root.Left == nil{
return minDepth(root.Right) + 1
}
return min(minDepth(root.Left), minDepth(root.Right)) + 1
}
func min(a, b int) int{
if a > b {
return b
}
return a
}
递归边界条件可以进行逻辑层面优化:
- 空节点的返回值为 0 (优化前置条件)
- 当前节点的左右子节点有至少一者为空时,返回 左子树深度 + 右子树深度 + 1
- 否则返回 min(左子树深度, 右子树深度) + 1
代码进行优化后
func minDepth(root *TreeNode) int {
if root == nil { return 0 }
if root.Left == nil || root.Right == nil{ return minDepth(root.Left) + minDepth(root.Right) + 1 }
return min(minDepth(root.Left), minDepth(root.Right)) + 1
}
func min(a, b int) int{
if a > b { return b }
return a
}