알고리즘/LeetCode
1026. Maximum Difference Between Node and Ancestor
앤테바
2022. 12. 9. 18:27
반응형
문제)
1026. Maximum Difference Between Node and Ancestor
Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.
A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.
Example 1:
Input: root = [8,3,10,1,6,null,14,null,null,4,7,13]
Output: 7
Explanation: We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
Example 2:
Input: root = [1,null,2,null,0,3]
Output: 3
Constraints:
- The number of nodes in the tree is in the range [2, 5000].
- 0 <= Node.val <= 105
솔루션1)
- 자식 노드 순회할 때 이전 부모 노드의 최대/최소 값을 전달해서 최대 diff를 계산
class Solution:
def __init__(self):
self.max_diff_val = 0
def maxAncestorDiff(self, root):
self.max_diff_val = 0
def _traverse(node, ancestor_max_val, ancestor_min_val):
if node is None:
return
self.max_diff_val = max(self.max_diff_val, abs(ancestor_max_val - node.val))
self.max_diff_val = max(self.max_diff_val, abs(ancestor_min_val - node.val))
ancestor_max_val = max(ancestor_max_val, node.val)
ancestor_min_val = min(ancestor_min_val, node.val)
_traverse(node.left, ancestor_max_val, ancestor_min_val)
_traverse(node.right, ancestor_max_val, ancestor_min_val)
_inorder(root, root.val, root.val)
return self.max_diff_val
솔루션2)
class Solution:
def maxAncestorDiff(self, root):
def _dfs(node, ancestor_min, ancestor_max):
if node is None:
return ancestor_max - ancestor_min
ancestor_max = max(ancestor_max, node.val)
ancestor_min = min(ancestor_min, node.val)
return max(_dfs(node.left, ancestor_min, ancestor_max), _dfs(node.right, ancestor_min, ancestor_max))
return _dfs(root, root.val, root.val)
반응형