[leetcode] 1026. Maximum Difference Between Node and Ancestor

Description

Given the root of a binary tree, find the maximum value V for which there exists 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: [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.

Note:

  1. The number of nodes in the tree is between 2 and 5000.
  2. Each node will have value between 0 and 100000.

分析

题目的意思是:求当前节点和祖先节点的最大绝对值差。大概思路是这样,我用cur_max记录当前祖先的最大值,用cur_min记录当前祖先的最小值,递归的每一个结点都跟最大值和最小值做绝对值差,然后取其中的最大绝对值差就行了。如果能够想到把祖先的最大值最小值当成参数往下传就能做出来了。

代码

# 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 solve(self,root,cur_max,cur_min):
        if(root is None):
            return 
        self.res=max(self.res,abs(cur_max-root.val),abs(cur_min-root.val))
        cur_min=min(cur_min,root.val)
        cur_max=max(cur_max,root.val)
     
        self.solve(root.left,cur_max,cur_min)
        self.solve(root.right,cur_max,cur_min)
       
        
    def maxAncestorDiff(self, root: TreeNode) -> int:
        self.res=0
        if(root is None):
            return self.res
        self.solve(root,root.val,root.val)
        return self.res

参考文献

[LeetCode] solution

猜你喜欢

转载自blog.csdn.net/w5688414/article/details/109270258
今日推荐