【LeetCode with Python】 Balanced Binary Tree

博客域名: http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/balanced-binary-tree/
题目类型:二叉树,递归回溯
难度评价:★★
本文地址: http://blog.csdn.net/nerv3x3/article/details/3465764

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 ofevery node never differ by more than 1.


判断一棵树是否高度平衡,即每个节点的左右子树高度相差不过1,参考BBT二叉平衡树或AVL的定义。还是用常见的二叉树递归回溯解法。


class Solution:
    def checkBBT(self, root):
        if None == root:
            return True, 0
        isLeftBBT, leftDepth = self.checkBBT(root.left)
        isRightBBT, rightDepth = self.checkBBT(root.right)
        isBBT = isLeftBBT and isRightBBT and abs(leftDepth - rightDepth) <= 1
        depth = max(leftDepth, rightDepth) + 1
        return isBBT, depth

    # @param root, a tree node
    # @return a boolean
    def isBalanced(self, root):
        return self.checkBBT(root)[0]

你可能感兴趣的:(LeetCode,with,Python,LeetCode,with,Python,LeetCode,Python,LeetCode,with,Python)