12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- package main
- import (
- "fmt"
- )
- type TreeNode struct {
- Val int
- Left *TreeNode
- Right *TreeNode
- }
- func maxInt(x, y int) int {
- if x > y {
- return x
- }
- return y
- }
- func abs(x int) int {
- if x < 0 {
- return -x
- }
- return x
- }
- func treeDepth(root *TreeNode, depth int) int {
- if root == nil {
- return depth
- }
- return maxInt(treeDepth(root.Left, depth+1), treeDepth(root.Right, depth+1))
- }
- /**
- * 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
- }
- if abs(treeDepth(root.Left, 0)-treeDepth(root.Right, 0)) > 1 {
- return false
- }
- return isBalanced(root.Left) && isBalanced(root.Right)
- }
- func main() {
- /**
- * t1: 5
- * / \
- * 1 4
- * / \
- * 2 3
- */
- t1l := TreeNode{1, nil, nil}
- t1rl := TreeNode{2, nil, nil}
- t1rr := TreeNode{3, nil, nil}
- t1r := TreeNode{4, &t1rl, &t1rr}
- t1 := &TreeNode{5, &t1l, &t1r}
- fmt.Println(isBalanced(t1))
- fmt.Println(isBalanced(nil))
- }
|