Skip to content

Latest commit

 

History

History
51 lines (37 loc) · 1.38 KB

_1026. Maximum Difference Between Node and Ancestor.md

File metadata and controls

51 lines (37 loc) · 1.38 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 23, 2024

Last updated : June 23, 2024


Related Topics : Tree, Depth-First Search, Binary Tree

Acceptance Rate : 78.07 %


Solutions

Python

# 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 maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
        def helper(curr: Optional[TreeNode], minn: int, maxx: int) -> int :
            if not curr :
                return maxx - minn

            if curr.val < minn :
                minn = curr.val
            if curr.val > maxx :
                maxx = curr.val

            return max(maxx - minn, 
                        helper(curr.left, minn, maxx), 
                        helper(curr.right, minn, maxx))


        return helper(root, root.val, root.val)