Re: [闲聊] 每日LeetCode

楼主: Rushia (みけねこ的鼻屎)   2022-12-09 11:24:43
1026. Maximum Difference Between Node and Ancestor
给予一个二元树,找出最大的值v,v为两个相异的节点a和b之值相减之绝对值,a必须
满足他是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:
https://assets.leetcode.com/uploads/2020/11/09/tmp-tree.jpg
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.
思路:
1.可以用dfs遍历所有节点,并记录父节点的最大值和最小值,最大的绝对值差一定是
当前节点减去最大或最小。
Java Code:
作者: pandix (面包屌)   2022-12-09 11:32:00
大师
作者: DDFox (冒险者兼清洁工)   2022-12-09 11:37:00
大师
作者: sustainer123 (caster)   2022-12-09 11:42:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com