首页 > 编程语言 >[LeetCode] 1315. Sum of Nodes with Even-Valued Grandparent 祖父节点值为偶数的节点和

[LeetCode] 1315. Sum of Nodes with Even-Valued Grandparent 祖父节点值为偶数的节点和

时间:2022-08-31 12:55:07浏览次数:83  
标签:Even node 1315 right res 结点 nodes 节点 left


Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0.

A grandparent of a node is the parent of its parent if it exists.

Example 1:

Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 18
Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.

Example 2:

Input: root = [1]
Output: 0

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • 1 <= Node.val <= 100

这道题给了一棵二叉树,让返回具有偶数值爷结点的所有结点的值之和,何为爷结点,就是父结点的父结点。需要找出所有爷结点值是偶数的结点,并返回它们的结点值之和,注意不是返回爷结点值之和。根据以往的经验,二叉树的题目大多情况下都是用递归的解法,这道题也不例外,遍历顺序就用先序遍历就可以了。在递归函数中,首先判空,若为空,直接返回。否则看当前结点值是否为偶数,是的话就去找其孙结点,一共有四个孙结点,若左子结点存在的话,分别判断其两个孙结点是否存在,存在的话就将其结点值加到 res 中,同理,若右子结点存在的话,分别判断其两个孙结点是否存在,存在的话就将其结点值加到 res 中,然后在分别对左右子结点调用递归函数即可,参见代码如下:


解法一:

class Solution {
public:
    int sumEvenGrandparent(TreeNode* root) {
        int res = 0;
        dfs(root, res);
        return res;
    }
    void dfs(TreeNode* node, int& res) {
        if (!node) return;
        if (node->val % 2 == 0) {
            if (node->left) {
                if (node->left->left) res += node->left->left->val;
                if (node->left->right) res += node->left->right->val;
            }
            if (node->right) {
                if (node->right->left) res += node->right->left->val;
                if (node->right->right) res += node->right->right->val;
            }
        }
        dfs(node->left, res);
        dfs(node->right, res);
    }
};

上面解法的判断有些复杂,这是因为是在找当前结点的四个孙结点,若是直接处理每个孙结点的话,就会相对简单一些。但此时必须要知道孙结点的爷结点,同时也要知道父结点,因为一旦去递归子结点时,之前的父结点就是新的爷结点,所以在递归函数中要把父结点和爷结点当参数传进去。在递归函数中还是先判空,然后判断若爷结点存在,并且值为偶数,则将当前结点值加到 res 中,然后分别对左右子结点调用递归函数,当前结点和父结点就变成了新的父结点和爷结点当参数传入即可,参见代码如下:


解法二:

class Solution {
public:
    int sumEvenGrandparent(TreeNode* root) {
        int res = 0;
        dfs(root, nullptr, nullptr, res);
        return res;
    }
    void dfs(TreeNode* node, TreeNode* parent, TreeNode* grandParent, int& res) {
        if (!node) return;
        if (grandParent && grandParent->val % 2 == 0) {
            res += node->val;
        }
        dfs(node->left, node, parent, res);
        dfs(node->right, node, parent, res);
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1315


参考资料:

https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/

https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/discuss/477095/Easy-DFS-solution

https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/discuss/477048/JavaC%2B%2BPython-1-Line-Recursive-Solution


LeetCode All in One 题目讲解汇总(持续更新中...)

标签:Even,node,1315,right,res,结点,nodes,节点,left
From: https://www.cnblogs.com/grandyang/p/16642713.html

相关文章

  • 以树状的形式封装有孩子的节点
    @OverridepublicList<CategoryEntity>listAsTree(){List<CategoryEntity>entities=baseMapper.selectList(null);List<CategoryEntity>lev......
  • 基于KubeEdge的边缘节点分组管理设计与实现
    摘要:KubeEdge1.11版本提供了“边缘节点分组管理”新特性,抽象出了跨地域的应用部署模型。本文分享自华为云社区《基于KubeEdge的边缘节点分组管理设计与实现》,作者:云容器......
  • stopPropagation, preventDefault 和 return false 的区别
    stopPropagation阻止事件的冒泡和捕获。因为事件可以在各层级的节点中传递,不管是冒泡还是捕获,有时我们希望事件在特定节点执行完之后不再传递,可以使用事件对象的s......
  • React报错之Property 'value' does not exist on type EventTarget
    正文从这开始~总览当event参数的类型不正确时,会产生"Property'value'doesnotexistontypeEventTarget"错误。为了解决该错误,将event的类型声明为React.ChangeEvent......
  • PXC集群脑裂导致节点是无法加入无主的集群
    一套2节点的MySQLPXC集群,第1节点作为主用节点长时间的dml操作,导致大量的事务阻塞,出现异常,此时查看第2节点显示是primary状态,但无事务阻塞情况。此时第1节点无法正常提供......
  • 链表节点删除
      代码:1importjava.util.*;23publicclassMain{4publicstaticvoidmain(String[]args){5Scannerscan=newScanner(System.in);......
  • vue 监听事件addEventListener
    vue添加监听事件addEventListener//vue添加监听事件,addEventListener第二个参数要绑在this上,即需要在methods中声明,否则销毁的时候会报错//在mounted中监听,在beforeD......
  • [Typescript] Step 3. Turn on "noImplicitAny" and even more strict mode
    Step3:Turnon"noImplicitAny"Fromprevioussteps,weallowimplicitany:https://www.cnblogs.com/Answer1215/p/16634618.html Now,weneedtoturnon"noIm......
  • 事件轮询Event loop
    事件轮询(eventloop)含义eventloop即事件轮询,这个是js里面为了解决单线程阻塞问题提出的解决方案,也是js异步执行机制的原理单线程众所周知,js执行是单线程的,什么是......
  • Airtest IDE 自动化测试9——text和keyevent
    前言在AirtestIDE的Airtest录制辅助窗内,包含有三种类型的录制按钮:操作类型辅助类型断言类型touchtextassert_existsswipekeyeventassert_not_exists......