LeetCode - 1026 Maximum Difference Between Node and Ancestor | Python Solution

LeetCode 1026 Python Solution

 LeetCode : https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/description/




# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    max_diff = 0
    def maxAncestorDiff(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def helper(root , cmin , cmax):
            if root is None :
                return float('inf') ,float('-inf') 

            #Traverse Tree   
            left_min , left_max = helper(root.left , cmin , cmax)
            right_min , right_max = helper(root.right , cmin ,cmax)

            cmin =  min(root.val , left_min , right_min )
            cmax=  max(root.val , left_max , right_max )

            self.max_diff = max(self.max_diff , abs(root.val - cmin) , abs(root.val - cmax))

            return (cmin , cmax)            

        helper(root, float('inf') ,float('-inf'))
        return self.max_diff     

Comments

Popular posts from this blog

JDBC Hive Connection fails : Unable to read HiveServer2 uri from ZooKeeper

Access Kubernetes ConfigMap in Spring Boot Application

Developing Custom Processor in Apache Nifi