The following is a coding challenge I'm working on.
You are given a binary tree in which each node contains a value. Design an algorithm to print all nodes whose subtree adds up to an even number.
This is the tree I'm working with for testing, together with my function:
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
const a = new Node(3);
const b = new Node(11);
const c = new Node(4);
const d = new Node(4);
const e = new Node(-2);
const f = new Node(2);
a.left = b;
a.right = c;
b.left = d;
b.right = e;
c.right = f;
// 3
// / \
// 11 4
// / \ \
// 4 -2 2
const isEven = (node) => {
if (node === null) return 0;
let left = isEven(node.left);
let right = isEven(node.right);
let sum = left + right + node.val;
if (sum % 2 === 0) {
console.log(node.val);
}
return;
};
console.log(isEven(a));
The function is not working the way I want it to.
Given this tree, I think the correct output should be: 3, 4, -2, 4 aka a, d, e and c. (assuming null = 0) But the output I'm getting is: 4, -2, 2, undefined
I'm not sure where the 2 is even coming from because no node is equal to 2. (That was a mistake on my part)