JZ39 平衡二叉树

平衡二叉树

题目:输入一棵二叉树,判断该二叉树是否是平衡二叉树。

在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
 
func maxDepth(root *TreeNode) int {
    if root == nil {
        return 0
    }  
    //不平衡的时候用-1表示
    left := maxDepth(root.Left)
    right := maxDepth(root.Right)
    
    if left == -1 || right == -1 || abs(left - right) > 1 {
        return -1
    }
    
    return max(left, right) + 1
}

func max(a, b int) int {
    if a < b {
        return b
    }
    return a
}

func abs(c int) int {
    if c < 0 {
        return -c
    }
    return c
}

func IsBalanced_Solution(root *TreeNode) bool {
    if root == nil {
        return true
    }
    
    return maxDepth(root) != -1
}

 

 

func abs(a, b int) int {
    if a - b > 0 {
        return a - b
    }

    return b - a
}
func IsBalanced_Solution( pRoot *TreeNode ) bool {
    // write code here
    if pRoot == nil {
        return true
    }

    if abs(Count(pRoot.Left), Count(pRoot.Right)) > 1 {
        return false
    }
    
    return IsBalanced_Solution(pRoot.Left) && IsBalanced_Solution(pRoot.Right)
}

func Count(root *TreeNode) int {
    if root == nil {
        return 0
    }

    left := Count(root.Left)
    right := Count(root.Right)
    if left > right {
        return left + 1
    }

    return right + 1
}

  

 

posted @ 2021-04-10 15:42  zqlucky  阅读(66)  评论(0编辑  收藏  举报