平衡二叉树

LeetCode题目地址

给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1

时间复杂度是O(n),后序遍历
参考文章二叉树

    def isBalancedTree(self, pRoot):
        if pRoot is None:
            return 0,True
        right,isBalancedRight = self.isBalancedTree(pRoot.right)
        left,isBalancedLeft = self.isBalancedTree(pRoot.left)
        depth = max(left, right) +1
        if isBalancedRight and isBalancedLeft:
            diff = abs(left - right)
            if diff <= 1:
                return depth,True
        return depth,False
            
    def isBalanced(self, root):
        # write your code here
        depth,isba = self.isBalancedTree(root)
        return isba

你可能感兴趣的:(平衡二叉树)