LintCode:平衡二叉树

116 篇文章 0 订阅

LintCode:平衡二叉树

先对树的每个节点求高度, 最后判断。

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
class Solution:
    """
    @param root: The root of binary tree.
    @return: True if this Binary tree is Balanced, or false.
    """
    def isBalanced(self, root):
        # write your code here
        if root == None:
            return True
        L = []
        self.pre_order(root, L)
        for i in L:
            if i > 1:
                return False
        return True
    #求每个节点的高度    
    def tree_depth(self, root):  
        if root == None:
            return 0

        l_depth = self.tree_depth(root.left)
        r_depth = self.tree_depth(root.right)

        return  (l_depth + 1) if (l_depth > r_depth)  else (r_depth + 1)

    def pre_order(self, root, L):
        if root == None:
            return
        l_d = self.tree_depth(root.left)
        r_d = self.tree_depth(root.right)
        L.append(abs(l_d - r_d))
        self.pre_order(root.left, L)
        self.pre_order(root.right, L)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值