Files
LeetCode-Go/leetcode/0110.Balanced-Binary-Tree/110. Balanced Binary Tree.go
2020-08-07 17:06:53 +08:00

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
}