LeetCode 111. 二叉树的最小深度Golang版

本文介绍了解决LeetCode111题目——求解二叉树最小深度的方法,提供了递归和迭代两种解决方案。递归方法通过深度优先搜索实现,迭代方法则采用广度优先搜索进行层序遍历。

LeetCode 111. 二叉树的最小深度Golang版

1. 问题描述

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明:叶子节点是指没有子节点的节点。
在这里插入图片描述

2. 思路

2.1. 递归

  1. 确定递归函数的参数和返回值
	func minDepth(root *TreeNode) int
  1. 确定终止条件
	if root == nil {
		return 0
	}
  1. 确定单层循环逻辑
	leftDepth := minDepth(root.Left)
	rightDepth := minDepth(root.Right)
	if root.Left == nil && root.Right != nil {
		return 1 + rightDepth
	}
	if root.Left != nil && root.Right == nil {
		return 1 + leftDepth
	}
	if leftDepth > rightDepth {
		leftDepth = rightDepth
	}
	return leftDepth + 1

2.2. 迭代

层序遍历模板题

3. 代码

3.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
    }

    leftDepth := minDepth(root.Left)
    rightDepth := minDepth(root.Right)

    if root.Left == nil && root.Right != nil {
        return 1 + rightDepth
    }
    if root.Left != nil && root.Right == nil {
        return 1 + leftDepth
    }

    if leftDepth > rightDepth {
        leftDepth = rightDepth
    }
    return leftDepth + 1
}

3.2. 迭代代码

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func minDepth(root *TreeNode) int {
    var res int
    if root == nil {
        return 0
    }

    queue := []*TreeNode{root}
    for len(queue) != 0 {
        length := len(queue)
        for i := 0; i < length; i++ {
            if queue[0].Left != nil {
                queue = append(queue, queue[0].Left)
            }
            if queue[0].Right != nil {
                queue = append(queue, queue[0].Right)
            }
            if queue[0].Left == nil && queue[0].Right == nil {
                return res + 1
            }
            queue = queue[1:]
        }
        res++
    }
    return res
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值