LeetCode104. 二叉树的最大深度Golang版
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
2. 思路
2.1. 递归
- 确定递归函数参数和返回值
func maxDepth(root *TreeNode) int
- 确定终止条件
if root == nil {
return 0
}
- 确定单层递归逻辑
leftDepth := maxDepth(root.Left)
rightDepth : maxDepth(root.Right)
if leftDepth < maxDepth {
leftDepth = rightDepth
}
return leftDepth + 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
}