Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Tuesday, May 3, 2022

Sum of Nodes with Even-Valued Grandparent Java Solution


Problem:

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

 

 Solution: 

public int sumEvenGrandparent(TreeNode root) {
        ArrayList<TreeNode> list = new ArrayList<>();
        fillList(root, list);
        int res = 0;
        for(TreeNode node: list) {
            res+= getSumOfGrandChild(node, 2);
        }
        return res;
    }
    public void fillList(TreeNode root, ArrayList<TreeNode> list) {
        if(root == null) return;
        if(root.val%2==0)
            list.add(root);
        fillList(root.left, list);
        fillList(root.right, list);
    }
    public int getSumOfGrandChild(TreeNode root, int depth) {
        if(root == null ) return 0;
        if(depth == 0) return root.val;
        if(depth < 0) return 0;
        return getSumOfGrandChild(root.left, depth-1) + getSumOfGrandChild(root.right, depth-1);
    }

0 Comments:

Post a Comment

Stats