[代码随想录]Day14-二叉树part03
题目:104. 二叉树的最大深度
思路:
本题可以使用前序(中左右),也可以使用后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度。
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)
而根节点的高度就是二叉树的最大深度。
前序递归三步:
- 参数就是深度和节点,不需要返回值留一个全局的res返回
- 空节点返回
- 前序的思路是,根节点深度与res比较留较大的(注意是从0开始还是从1开始),之后再去走左右。
后续递归三步:
- 参数是深度和节点,需要一个返回值是最大的深度
- 空节点返回
- 后序的思路是,记录左节点深度和有节点深度,把结果记录在根节点上,之后逐层向上返回。
代码1:
前序递归
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var res int
func maxDepth(root *TreeNode) int {
res = 0
CalcDepth(root,1)
return res
}
func CalcDepth(root *TreeNode,deepth int) {
if root == nil {
return
}
res = max(res, deepth)
CalcDepth(root.Left, deepth+1)
CalcDepth(root.Right, deepth+1)
return
}
func max(a,b int) int {
if a > b {
return a
}
return b
}
代码2:
后续递归 - 速度更快
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxDepth(root *TreeNode) int {
return CalcDepth(root, 0)
}
func CalcDepth(root *TreeNode,deepth int) int {
if root == nil {
return 0;
}
leftDepth := CalcDepth(root.Left,deepth+1)
rightDepth := CalcDepth(root.Right,deepth+1)
rootDepth := 1 + max(leftDepth,rightDepth) // 倒数第几层
return rootDepth
// 可以把以上四行简化为下面一行
// return 1 + max(CalcDepth(root.Left,deepth+1),CalcDepth(root.Right,deepth+1))
}
func max(a,b int) int {
if a > b {
return a
}
return b
}
参考:
题目:111. 二叉树的最小深度
思路:
思路和上面的后续一样,注意一点:

要特殊判断只有一个孩子节点的子节点。
左右都没有节点才能算是一个叶子节点。
代码:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minDepth(root *TreeNode) int {
return calcMinDepth(root,0)
}
func calcMinDepth(root *TreeNode,depth int) int {
if root == nil {
return 0
}
if root.Left == nil && root.Right != nil { // 不能算单侧
return 1 + calcMinDepth(root.Right, depth+1)
}
if root.Right == nil && root.Left != nil {
return 1 + calcMinDepth(root.Left, depth+1)
}
return 1 + min(calcMinDepth(root.Left ,depth+1),calcMinDepth(root.Right, depth+1))
}
func min(a,b int)int {
if a < b{
return a
}
return b
}
参考:
题目:222. 完全二叉树的节点个数
思路:
本身自己也是一个节点,所以返回 1 + left + right
代码:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func countNodes(root *TreeNode) int {
if root == nil {
return 0;
}
left := countNodes(root.Left)
right := countNodes(root.Right)
return 1 + left + right
}

浙公网安备 33010602011771号