平衡二叉树

2018-05-02  本文已影响2人  只为此心无垠

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
上一篇下一篇

猜你喜欢

热点阅读