leetcode 1315. Sum of Nodes with Even-Valued Grandparent

Posted 琴影

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 1315. Sum of Nodes with Even-Valued Grandparent相关的知识,希望对你有一定的参考价值。

Given a binary tree, return the sum of values of nodes with even-valued grandparent.  (A grandparent of a node is the parent of its parent, if it exists.)

If there are no nodes with an even-valued grandparent, return 0.

 

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.

 

Constraints:

  • The number of nodes in the tree is between 1 and 10^4.
  • The value of nodes is between 1 and 100.

题目大意:计算树中所有祖父结点值为偶数的结点值的和。

方法一:直接用深搜的递归做法:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 private:
14     int dfs(TreeNode *root, TreeNode *parent, TreeNode *grandParent) {
15         if (root == nullptr) return 0;
16         int sum = 0;
17         if ((grandParent != nullptr) && ((grandParent->val & 1) == 0))
18             sum = root->val;
19         return sum + dfs(root->left, root, parent) + dfs(root->right, root, parent);
20     }
21 public:
22     int sumEvenGrandparent(TreeNode* root) {
23         if (root == nullptr)
24             return 0;
25         return dfs(root, nullptr, nullptr);
26     }
27 };

 

以上是关于leetcode 1315. Sum of Nodes with Even-Valued Grandparent的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 1315. Sum of Nodes with Even-Valued Grandparent

[LeetCode] 1315. Sum of Nodes with Even-Valued Grandparent

1315. 祖父节点值为偶数的节点和

1315. 祖父节点值为偶数的节点和

1315. 祖父节点值为偶数的节点和

算法1315. 祖父节点值为偶数的节点和(多语言实现)