【LeetCode】110. Balanced Binary Tree

两种解法:

(1)暴力法,自顶向下:

    遍历每个节点,递归法求每个节点的左右子树最大深度,并用递归法判断该树是否平衡。时间复杂度O(n^2),空间复杂度O(n)

(2)自底向上递归法:

    同我的心路,但代码更简洁一丢丢。

Python源码:

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

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.max_depth(root) != -1:
         
    def max_depth(self, node):
        if node == None:
            return 0
        left_depth = self.get_depth(node.left)
        right_depth = self.get_depth(node.right)
        if left_depth == -1 or right_depth == -1:
            return -1
        if abs(left_depth - right_depth) > 1:
            return -1
        else:
            return max(left_depth, right_depth) + 1

我的心路:

    对平衡二叉树的概念不清,所以错误地采用了bfs方法进行搜索,产生错误。

    重新阅读平衡二叉树的定义,定义中指出,二叉树中每一节点的左右子树的深度差值均不大于1时,二叉树为平衡二叉树。

    采用递归方法,深度优先遍历二叉树,当某一节点的左右子树深度差值大于1时返回-1,否则返回该节点的深度。

Runtime: 44 ms, faster than 57.90% of Python online submissions for Balanced Binary Tree.

Memory Usage: 16.4 MB, less than 71.88% of Python online submissions for Balanced Binary Tree.

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

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if self.get_depth(root) == -1:
            return False
        else:
            return True
        
        
    def get_depth(self, node):
        if node == None:
            return 0
        left_depth = self.get_depth(node.left)
        right_depth = self.get_depth(node.right)
        if left_depth == -1 or right_depth == -1:
            return -1
        if abs(left_depth - right_depth) > 1:
            return -1
        else:
            return max(left_depth, right_depth) + 1

 

你可能感兴趣的:(Python,LeetCode,算法基础)