0
点赞
收藏
分享

微信扫一扫

【LeetCode】111. 二叉树的最小深度(错题2刷)

Alex富贵 2022-02-12 阅读 156

0
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
    }
    queue := []*TreeNode{root}
    res := 0
    for len(queue) > 0 {
        curLen := len(queue)
        res++
        for i := 0; i < curLen; i++ {	// 遍历当前层
            node := queue[0]
            queue = queue[1:]
            if node.Left != nil {
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
            if node.Left == nil && node.Right == nil {
                return res
            }
        }
    }
    return res
}

// 递归法
func min(a, b int) int {
    if a > b {
        return b
    }
    return a
}
func minDepth(root *TreeNode) int {
    if root == nil {
        return 0
    }
    // 左
    left := minDepth(root.Left)
    // 右
    right := minDepth(root.Right)
    // 中
    // 两种有一个为空的情况,需要返回的是不为空那边的最小深度
    if root.Left != nil && root.Right == nil {
        return 1 + left
    }
    if root.Left == nil && root.Right != nil {
        return 1 + right
    }
    // 都为空
    return 1 + min(left, right)
}

4

举报

相关推荐

0 条评论