LintCode:平衡二叉树

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)
    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/u012225151/article/details/51255098
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞