树-节点祖先问题(2)

1026. 节点与其祖先之间的最大差值
给定二叉树的根节点 root,找出存在于不同节点 A 和 B 之间的最大值 V,其中 V = |A.val - B.val|,且 A 是 B 的祖先。

(如果 A 的任何子节点之一为 B,或者 A 的任何子节点是 B 的祖先,那么我们认为 A 是 B 的祖先)

 

示例:



输入:[8,3,10,1,6,null,14,null,null,4,7,13]
输出:7
解释: 
我们有大量的节点与其祖先的差值,其中一些如下:
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
在所有可能的差值中,最大值 7 由 |8 - 1| = 7 得出。
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    res = 0
    def maxAncestorDiff(self,root:TreeNode)->int:
        if not root: return 0
        self.dfs(root,root.val, root.val)
        return self.res
    def dfs(self,root, maxValue, minValue):
        maxValue = max(root.val, maxValue)
        minValue = min(root.val, minValue)
        if root.left is None and root.right is None:
            self.res = max(self.res, abs(maxValue - minValue))
        if root.left:
            self.dfs(root.left,maxValue,minValue)
        if root.right:
            self.dfs(root.right,maxValue,minValue)
1315. 祖父节点值为偶数的节点和
给你一棵二叉树,请你返回满足以下条件的所有节点的值之和:

该节点的祖父节点的值为偶数。(一个节点的祖父节点是指该节点的父节点的父节点。)
如果不存在祖父节点值为偶数的节点,那么返回 0 。
输入:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
输出:18
解释:图中红色节点的祖父节点的值为偶数,蓝色节点为这些红色节点的祖父节点。
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sumEvenGrandparent(self, root: TreeNode) -> int:
        ans = 0

        def dfs(gp_val, p_val, node):
            if not node:
                return
            if gp_val % 2 == 0:
                nonlocal ans
                ans += node.val
            dfs(p_val, node.val, node.left)
            dfs(p_val, node.val, node.right)
        
        dfs(1, 1, root)
        return ans
好好学习,天天向上
原文地址:https://www.cnblogs.com/topass123/p/13375493.html