Count

Implementing a function that counts all the nodes in the trees is quite trivial now that we are beginning to grasp the nature of recursion. We can reuse our summary function from before and simply count every non-null node as 1 and null as 0. So, we simply take the existing summary function and modify it to this:

//tree-count.js

const root = require("./tree");

function count(node) {
if (node === null) {
return 0;
} else {
return 1 + count(node.left) + count(node.right);
}
}

console.log("count", count(root));

The preceding code ensures we traverse each and every node successfully. Our exit condition happens when we reach null. That is, we are trying to go from a node to one of its non-existing children.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.111.118