알고리즘/LeetCode
LeetCode 풀기 - 1026. Maximum Difference Between Node and Ancestor
앤테바
2021. 12. 31. 20:48
반응형
1026. Maximum Difference Between Node and Ancestor
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/
Maximum Difference Between Node and Ancestor - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제)
솔루션1) Recursive
Consistency is a key!!!
2021년 마지막 문제 풀이입니다.
# 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 recur(node, min_val, max_val):
if node is None:
return 0
max_diff = max(abs(min_val - node.val), abs(max_val - node.val))
min_val = min(min_val, node.val)
max_val = max(max_val, node.val)
return max(recur(node.left, min_val, max_val), recur(node.right, min_val, max_val), max_diff)
return recur(root, root.val, root.val)
반응형