mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-04 16:12:47 +08:00
48 lines
751 B
Go
48 lines
751 B
Go
package leetcode
|
|
|
|
import (
|
|
"github.com/halfrost/LeetCode-Go/structures"
|
|
)
|
|
|
|
// TreeNode define
|
|
type TreeNode = structures.TreeNode
|
|
|
|
/**
|
|
* Definition for a binary tree node.
|
|
* type TreeNode struct {
|
|
* Val int
|
|
* Left *TreeNode
|
|
* Right *TreeNode
|
|
* }
|
|
*/
|
|
|
|
func isBalanced(root *TreeNode) bool {
|
|
if root == nil {
|
|
return true
|
|
}
|
|
leftHight := depth(root.Left)
|
|
rightHight := depth(root.Right)
|
|
return abs(leftHight-rightHight) <= 1 && isBalanced(root.Left) && isBalanced(root.Right)
|
|
}
|
|
|
|
func depth(root *TreeNode) int {
|
|
if root == nil {
|
|
return 0
|
|
}
|
|
return max(depth(root.Left), depth(root.Right)) + 1
|
|
}
|
|
|
|
func abs(a int) int {
|
|
if a > 0 {
|
|
return a
|
|
}
|
|
return -a
|
|
}
|
|
|
|
func max(a int, b int) int {
|
|
if a > b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|