***LeetCode110 Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.

<思路>遍历每个点,比较每个点左子树与右子树高度差。其中设置if l==0 or r==0的原因是:如果之前遍历到某一个点,abs(l-r)>1了,返回的是-1,再递归的时候,l或r就是1+(-1)等于0,继续返回-1,直到递归结束。

这个题想的比较久

# 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
        """        
        def depth(root):
            if root is None:
                return 0
            l = 1 + depth(root.left)
            r = 1 + depth(root.right)
            if l==0 or r==0 or abs(l-r)>1:
                return -1
            return max(l,r)
        
        return depth(root)!=-1

另discuss中的迭代方法,值得学习借鉴。

class Solution(object):
    def isBalanced(self, root):
        stack, node, last, depths = [], root, None, {}
        while stack or node:
            if node:
                stack.append(node)
                node = node.left
            else:
                node = stack[-1]
                if not node.right or last == node.right:
                    node = stack.pop()
                    left, right  = depths.get(node.left, 0), depths.get(node.right, 0)
                    if abs(left - right) > 1: return False
                    depths[node] = 1 + max(left, right)
                    last = node
                    node = None
                else:
                    node = node.right
        return True

猜你喜欢

转载自blog.csdn.net/AIpush/article/details/82468999