github.com/benz9527/toy-box/algo@v0.0.0-20240221120937-66c0c6bd5abd/tree/balanced_binary_tree.go (about) 1 package tree 2 3 func IsHeightBalanced(n *Node, h int) (bool, int) { 4 if n == nil { 5 h = 0 6 return true, 0 7 } 8 9 l, lh := IsHeightBalanced(n.Left, 0) 10 r, rh := IsHeightBalanced(n.Right, 0) 11 12 if lh > rh { 13 h = lh + 1 14 } else { 15 h = rh + 1 16 } 17 18 if lh-rh >= 2 || 19 rh-lh >= 2 { 20 return false, h 21 } 22 23 return l && r, h 24 }