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.

hint1:Traverse the tree keeping the parent and the grandparent.
hint2:If the grandparent of the current node is even-valued, add the value of this node to the answer.

  public int sumEvenGrandparent(TreeNode root) {
        return helper(root, 1, 1);
    }

    public int helper(TreeNode node, int p, int gp) {
        if (node == null) return 0;
        return helper(node.left, node.val, p) + helper(node.right, node.val, p) + (gp % 2 == 0 ? node.val : 0);
    }
 class Solution {
	    public int sumEvenGrandparent(TreeNode root) {
	    return helper(root,null,null); //Perform DFS
	    }    
	  private int helper(TreeNode current,TreeNode parent,TreeNode grandParent){
	    int sum=0;
	    if(current==null) return 0;
	    if(grandParent!=null && grandParent.val % 2 == 0){
	         sum+=current.val;
	    }
	    sum+= helper(current.left,current,parent);
	    sum+=helper(current.right,current,parent);
	    return sum;
	}
}
public int sumEvenGrandparent(TreeNode root) {
        int sum = 0;
        Queue<TreeNode> q = new LinkedList();
        q.add(root);
        
        //LevelOrderTraversal
        while(!q.isEmpty()) {
            TreeNode node = q.poll();
            if(node.left != null) {
                q.add(node.left);
                if(node.val % 2 == 0) {
                    if(node.left.left != null) {
                        sum += node.left.left.val;
                    }
                    if(node.left.right != null) {
                        sum += node.left.right.val;
                    }
                }
            }

            if(node.right != null) {
                q.add(node.right);
                if(node.val % 2 == 0) {
                    if(node.right.left != null) {
                        sum += node.right.left.val;
                    }
                    if(node.right.right != null) {
                        sum += node.right.right.val;
                    }
                }
            }
        }
        
        return sum;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值