python实现 判断平衡二叉树

代码如下:

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
    def isBalanced(self, root):
        """ :type root: TreeNode :rtype: bool """
        def height(node):
            if not node:return 0
            left = height(node.left)
            right = height(node.right)
            if left == -1 or right == -1 or abs(left-right) > 1:
                return -1

            return max(left,right) + 1
        return height(root) != -1
    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/wyisfish/article/details/79426150
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞