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 } LeftDepth:= maxDepth(root.Left) rightDepth:= maxDepth(root.Right) if LeftDepth > rightDepth { return LeftDepth+1 } return rightDepth+1 } //或者加个判断 func maxDepth(root *TreeNode) int { // 节点空直接返回 if root == nil { return 0 } var LeftDepth = 0 var rightDepth = 0 if root.Left != nil { LeftDepth = maxDepth(root.Left) } if root.Right != nil { rightDepth = maxDepth(root.Right) } if LeftDepth > rightDepth { return LeftDepth+1 } return rightDepth+1 } 2. 二叉树的最小深度 /** * 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) // 左子树为0,返回右子树深度+1,或者右子树为0,返回左子树深度+1 if LeftDepth == 0 || RightDepth == 0{ return LeftDepth + RightDepth + 1 } if LeftDepth > RightDepth { return RightDepth+1 } return LeftDepth+1 }