题目:最大深度问题
题目链接:LeetCode-104. 二叉树的最大深度
思路分析:递归 + (节点最大深度=其左右节点最大深度+1)
Go代码
func maxDepth( root *TreeNode) int {
if root == nil {
return 0
}
return max( maxDepth( root.Left) , maxDepth( root.Right)) + 1
}
func max( a, b int) int {
if a >= b {
return a
}
return b
}
题目:判断平衡树
题目链接:LeetCode-110. 平衡二叉树
思路分析:递归(后序遍历) + 从叶子节点开始判断并返回是否平衡子树
Go代码
func isBalanced( root *TreeNode) bool {
if root == nil {
return true
}
return length( root) >= 0
}
func length( node *TreeNode) int {
if node == nil {
return 0
}
leftl := length( node.Left)
rightl := length( node.Right)
if leftl == -1 || rightl == -1 || abs( leftl-rightl) > 1 {
return -1
}
return max( length( node.Left) , length( node.Right)) + 1
}
func max( a,b int) int {
if a > b {
return a
}
return b
}
func abs( num int) int {
if num < 0 {
return -1 * num
}
return num
}
题目:最小深度问题
题目链接:LeetCode-111. 二叉树的最小深度
思路分析:递归 + (节点最小深度=其左右节点最小深度+1) + 考虑纯左子树 或 纯右子树
Go代码
func minDepth( root *TreeNode) int {
if root == nil {
return 0
}
if root.Left == nil && root.Right == nil {
return 1
}
if root.Left == nil {
return minDepth( root.Right) + 1
}
if root.Right == nil {
return minDepth( root.Left) + 1
}
return min( minDepth( root.Left) , minDepth( root.Right)) + 1
}
func min( a, b int) int {
if a <= b {
return a
}
return b
}
题目:N叉树的最大深度
题目链接:LeetCode-559. N 叉树的最大深度
思路分析:递归 +(节点最大深度=其所有子节点最大深度+1)
Go代码
func maxDepth( root *Node) int {
if root == nil {
return 0
}
max := 0
for _, v := range root.Children {
depth := maxDepth( v)
if depth > max {
max = depth
}
}
return max+1
}