爲啥沒有38?
因爲38沒過審。
今天點了十張圖,登陸上了。
題目
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.
分析
題意:如果當前節點父節點的父節點是偶數,那就把當前節點累加到結果中。
個人理解,這道題考察的是實現(在遞歸中的)記憶功能。
最簡單的想法:
爲每一個節點賦予一個deep變量進行深度記錄。
如果當前節點爲偶數,就往下進入兩層,通過deep記錄深度;
如果上述操作成功,就將該“孫子”節點值累加到結果中。
但是,事先並不知道節點數是多少,因此deep的個數不能事先確定。
如果使用局部變量…
打住!
想複雜了,就是簡單的傳值。
正常情況下,當前節點只能知道自己的兒子是誰(root.left\right),無法知道自己的父親,更不能知道自己的爺爺。
但是,我們調用的時候,可以“把父親傳遞下去”,父傳子,子傳孫。同理孫找父,再找爺爺,只需要順着這條繼承鏈上來就行了。
解答
把父親傳遞下去
算法中也傳遞了爺爺,但是實際上傳遞的還是當前類的父親。當前狀態實際是在父親這一輩。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int sum=0;
public int sumEvenGrandparent(TreeNode root) {
// 一開始root是祖宗,沒有父親,也沒有爺爺
helper(root, -1, -1);
return sum;
}
// node:當前的你、p:爸爸、gp:爺爺
public void helper(TreeNode node, int p, int gp) {
if (node == null) return;
// 如果爺爺是偶數,符合題意,把你加到結果集
if(gp%2==0) sum+=node.val;
// 你的左(右)二子,你爸,你爸的爸爸(爺爺)
helper(node.left,node.val,p);
helper(node.right,node.val,p);
}
}