Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.0 kB
3
Indexable
Never
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        def height(node):
            if node is None:
                return 0
            
            left=height(node.left)
            right=height(node.right)
            
            return 1+max(left,right)
        
        def check(node):
            
            left=height(node.left)
            right=height(node.right)
            
            if(abs(left-right)>1):
                return False
            
            return True
        
        def dfs(node,prev):
            
            if not node:
                return
            
            if node!=prev:
                if(not check(node)):
                    return False
                dfs(node.left,node)
                dfs(node.right,node)
        
        dfs(root,None)