Summarise

Thereafter, we need to think about how to summarise the nodes. Just looking at it, it looks like we should summarise the top node and its two children. So, a code implementation would start off like this:

// tree-sum.js

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

function summarise(node) {
return node.value + node.left.value + node.right.value;
}

console.log(summarise(root)) // 10

What happens if our tree grows and suddenly looks like this:

Let's add to the preceding code so it looks like this:

// example of a non recursive code

function summarise(node) {
return node.value +
node.left.value +
node.right.value +
node.right.left.value +
node.right.right.value +
node.left.left.value +
node.left.right.value;
}

console.log(summarise(root)) // 19

This is technically working code, but it can be improved. What we should see at this point, looking at the tree, are reoccurring patterns in the tree. We have the following triangles:

One triangle is made up of 2, 3, 5, another one is made up of 3, 1, 2, and the last one is made up of 5, 4, 2. Every triangle computes its sum by taking the node itself, plus its left child and its right child. Recursion is all about this: discovering a reoccurring pattern and codifying it. We can now implement our summarise() function with recursion, like so:

function summarise(node) {
if(node === null) {
return 0;
}
return node.value + summarise(node.left) + summarise(left.right);
}

What we are doing here is expressing our reoccurring pattern as node + left node + right node. When we call summarise(node.left) we simply run through summarise() again for that node. The preceding implementation is short and elegant, and is able to traverse the entire tree. Recursion is truly elegant once you find that your problem can be seen as a repeating pattern. The full code looks like this:

// tree.js

class NodeClass {
constructor(left, right, value) {
this.left = left;
this.right = right;
this.value = value;
}
}

const leftLeftLeftChild = new NodeClass(null, null, 7);
const leftLeftChild = new NodeClass(leftLeftLeftChild, null, 1);
const leftRightChild = new NodeClass(null, null, 2);
const rightLeftChild = new NodeClass(null, null, 4);
const rightRightChild = new NodeClass(null, null, 2);
const left = new NodeClass(leftLeftChild, leftRightChild, 3);
const right = new NodeClass(rightLeftChild, rightRightChild, 5);
const root = new NodeClass(left, right, 2);

module.exports = root;

// tree-sum.js

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

function sum(node) {
if (node === null) {
return 0;
}
return node.value + sum(node.left) + sum(node.right);
}

console.log("sum", sum(root));
..................Content has been hidden....................

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