平衡二叉树

题目:

一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例1:
给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7 

返回 true
示例2:
给定二叉树 [1,2,2,3,3,null,null,4,4]

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4
 
返回 false 
代码:
type Node struct {
	Left *Node
	Rigth *Node
	Value int64
}

func IsBlanceTree(root *Node) bool {
	if root == nil {
		return true
	}

	if !IsBlanceTree(root.Left) || !IsBlanceTree(root.Rigth) {
		return false
	}

	lHight := GetMaxDeep(root.Left)
	rHight := GetMaxDeep(root.Rigth)
	
	if Abs(lHight - rHight) > 1 {
		return false
	}

	return true
}

func GetMaxDeep(root *Node) int {
	if root == nil {
		return 0
	}

	return Max(GetMaxDeep(root.Left), GetMaxDeep(root.Rigth)) + 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
}

  地址:https://mp.weixin.qq.com/s/hBRfb3LpqDrB-I0mrPJmIA

posted @ 2020-09-27 10:50  small_lei_it  阅读(158)  评论(0编辑  收藏  举报