Here's my code to set up tree nodes.
class TreeNode {
constructor(value, left, right, level) {
this.value = value;
this.left = left;
this.right = right;
this.level = level
}
}
Here's my code to find the leftmost node at each tree level.
function findFirstNodes(root) {
const stack = [root];
root.level = 0;
const firsts = [];
while (stack.length > 0) {
const curr = stack.pop();
if (firsts[curr.level]) {
firsts.push(curr.value);
};
if (curr.left) {
stack.unshift(curr.left);
};
};
return firsts;
};
Here's my test code.
const simpleTree = new TreeNode(4, null, null);
simpleTree.right = new TreeNode(8, null, null);
simpleTree.left = new TreeNode(3, null, null);
simpleTree.right.right = new TreeNode(2, null, null);
console.log(findFirstNodes(simpleTree)); // -> [ 4, 3, 2 ]
Yet my result array comes out empty.
I have a general good grasp on the knowledge of how to traverse trees and such, but many of the details are still rusty to me. The code doesn't result in any errors, but the array just comes out empty. I tried console logging the curr variable when the tree is traversed, but I only get the one with 3.
curr.levelif thelevelproperty isundefinedfor all nodes in the test code?