题目
题目链接:https://leetcode-cn.com/problems/sum-of-nodes-with-even-valued-grandparent/
题目解析:
暴力遍历:
- 如果遇到结点是偶数
- 就搜索他的子节点的子节点,并加起来
代码:
/**
* 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) {
go(root);
return sum;
}
private void go(TreeNode root) {
//如果结点不为空
if(root!=null){
//System.out.print(root.val+"(");
//如果结点为偶数就搜索他的孙结点
if(root.val%2==0) {
//如果他的左子树不为空
if(root.left!=null){
TreeNode rootleft = root.left;
//就搜索他左子树的子节点
if(rootleft.left!=null) {
sum = sum + rootleft.left.val;
//System.out.print(rootleft.left.val+" ");
}
if(rootleft.right!=null) {
sum = sum + rootleft.right.val;
//System.out.print(rootleft.right.val+" ");
}
}
//如果他的右子树不为空
if(root.right!=null){
TreeNode rootright = root.right;
//就搜索他右子树的子节点
if(rootright.left!=null) {
sum = sum + rootright.left.val;
//System.out.print(rootright.left.val+" ");
}
if(rootright.right!=null) {
sum = sum + rootright.right.val;
//System.out.print(rootright.right.val+" ");
}
}
//System.out.print(")"+" ");
}
//System.out.print(")"+" ");
//遍历左子树
go(root.left);
//遍历右子树
go(root.right);
}
return;
}
}