算法:
这一类题目很简单,不过却是树的最基本操作之一,引申为判断树是不是平衡二叉树。
一般做法是,计算二叉树的左右子树的高度+1,然后取它们的最大值或者最小值。
题目1:
https://leetcode-cn.com/problems/balanced-binary-tree/
![]()
代码实现:
func isBalanced(root *TreeNode) bool { if root == nil { return true } lH := maxDepth(root.Left) rH := maxDepth(root.Right) if abs(lH-rH) > 1{ return false } if !isBalanced(root.Left) { return false } return isBalanced(root.Right)}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}func abs(a int) int { if a < 0 { return -a } return a}
执行结果:
![]()
题目2:
https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
![]()
代码实现:
func maxDepth(root *TreeNode) int { if root == nil { return 0 } left := maxDepth(root.Left) right := maxDepth(root.Right) if left > right { return left + 1 } return right + 1}
执行结果:
![]()
题目3:
https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
![]()
代码实现:
func minDepth(root *TreeNode) int { if root == nil { return 0 } if root.Left ==nil && root.Right == nil { return 1 } min := int(^uint(0) >> 1) if root.Left != nil { h := minDepth(root.Left) if min > h { min = h } } if root.Right != nil { h := minDepth(root.Right) if min > h { min = h } } return min+1}
执行结果:
![]()
题目4:
https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/
![]()
代码实现:
func maxDepth(root *Node) int { if root == nil { return 0 } var hs []int for _, n := range root.Children { h := maxDepth(n) hs = append(hs,h) } max := 0 for _,h:=range hs { if h > max { max = h } } return max + 1}
执行结果:
![]()