Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 파이썬릿코드풀기
- 잇츠디모
- 코틀린기초
- 상가수익률계산기
- 파이썬 알고리즘 풀기
- python xor
- LeetCode
- python 릿코드
- python sorted
- 릿코드풀기
- 알고리즘풀기
- binary search
- leetcode 풀기
- python Leetcode
- 릿코드 파이썬
- 릿코드 풀기
- 파이썬릿코드
- 릿코드풀이
- 파이썬 프로그래머스
- 파이썬 릿코드
- 알고리즘풀이
- 파이썬 알고리즘
- leetcode풀이
- python zip_longest
- python 알고리즘
- 파이썬알고리즘풀기
- 파이썬알고리즘
- python priority queue
- leetcode풀기
- 릿코드
Archives
- Today
- Total
소프트웨어에 대한 모든 것
1026. Maximum Difference Between Node and Ancestor 본문
반응형
문제)
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)
반응형
'알고리즘 > LeetCode' 카테고리의 다른 글
931. Minimum Falling Path Sum (0) | 2022.12.13 |
---|---|
2432. The Employee That Worked on the Longest Task (0) | 2022.12.09 |
6. Zigzag Conversion (0) | 2022.12.07 |
462. Minimum Moves to Equal Array Elements II (0) | 2022.07.01 |
5. Longest Palindromic Substring (0) | 2022.05.24 |
Comments