LeetCode104. 二叉树的最大深度Golang版

LeetCode104. 二叉树的最大深度Golang版

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

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

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

2. 思路

2.1. 递归

  1. 确定递归函数参数和返回值
	func maxDepth(root *TreeNode) int
  1. 确定终止条件
	if root == nil {
		return 0
	}
  1. 确定单层递归逻辑
	leftDepth := maxDepth(root.Left)
	rightDepth : maxDepth(root.Right)
	if leftDepth < maxDepth {
		leftDepth = rightDepth
	}
	return leftDepth + 1
  1. 完整代码
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func maxDepth(root *TreeNode) int {
    if root == nil {
        return 0
    }

    i := 0
    j := 0

    i = maxDepth(root.Left) + 1
    j = maxDepth(root.Right) + 1

    if i < j {
        i, j = j, i
    } 
    return i
}

2.2. 迭代(层序遍历)

这是一道层序遍历模板题

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

    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)
            }
            queue = queue[1:]
        }
        res++
    }
    return res
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值