美文网首页LeetCode By Go
[LeetCode By Go 93]110. Balanced

[LeetCode By Go 93]110. Balanced

作者: miltonsun | 来源:发表于2017-09-05 18:16 被阅读28次

    题目

    Given a binary tree, determine if it is height-balanced.

    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

    解题思路

    判断一个二叉树是否平衡,需要先清楚平衡二叉树的概念。概念清楚了题目就简单了,先判断根节点的左右子节点的高度差是否不大于1,然后递归判断子节点,如果有高度差大于1的节点,则该树不是平衡二叉树。
    平衡二叉树

    1. 可以是空树。
    2. 假如不是空树,任何一个结点的左子树与右子树都是平衡二叉树,并且高度之差的绝对值不超过1

    如定义,假如一棵树的左右子树的高度之差超过1,如左子树的树高为2,右子树的树高为0,子树树高差的绝对值为2就打破了这个平衡。如依次插入1,2,3三个结点(如下图)后,根结点的右子树树高减去左子树树高为2,树就失去了平衡。

    image.png

    树的深度

    1. 如果一棵树只有一个结点,它的深度为1。
    2. 如果根结点只有左子树而没有右子树,那么树的深度应该是其左子树的深度加1;同样如果根结点只有右子树而没有左子树,那么树的深度应该是其右子树的深度加1。
    3. 如果既有右子树又有左子树,那该树的深度就是其左、右子树深度的较大值再加1。

    代码

    /**
     * Definition for a binary tree node.
     * type TreeNode struct {
     *     Val int
     *     Left *TreeNode
     *     Right *TreeNode
     * }
     */
    
    func Height(t *TreeNode) (h int)  {
        if nil == t {
            return 0
        }
        left := Height(t.Left)
        right := Height(t.Right)
    
        if left == 0 && right == 0 {
            return 1
        } 
        
        if left > right {
            return left + 1
        } else {
            return right + 1
        }
    
    }
    
    func isBalanced(root *TreeNode) bool {
        if nil == root {
            return true
        }
    
        diff := Height(root.Left) - Height(root.Right)
        if diff < -1 || diff > 1 {
            return false
        }
    
        if isBalanced(root.Left)  && isBalanced(root.Right) {
            return true
        }
    
        return false
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 93]110. Balanced

        本文链接:https://www.haomeiwen.com/subject/gnhpjxtx.html