Old Wei wins the offer to take you to learn --- Brush title series (39. balanced binary tree)

39. The balanced binary tree

problem:

Input binary tree, the binary tree is determined whether a balanced binary tree.

solve:

thought:

Refers to a balanced binary tree height difference is no greater than about subtree tree 1 (containing an empty tree).

python code:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from collections import deque
class Solution:
    def IsBalanced_Solution(self, pRoot):
        # write code here
        if(pRoot==None):
            return True
        if(abs(self.deep(pRoot.left)-self.deep(pRoot.right))>1):
            return False
        return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)

    def deep(self,node):
        if(node==None):
            return 0
        nleft=self.deep(node.left)
        nright=self.deep(node.right)
        return max(nleft+1,nright+1)
            
        
        
Published 160 original articles · won praise 30 · views 70000 +

Guess you like

Origin blog.csdn.net/yixieling4397/article/details/105028594