/  Technology   /  How to get sum of children and check if it’s equal to root in Javascript?
How to get sum of children and check if it's equal to root?

How to get sum of children and check if it’s equal to root in Javascript?

Let us consider Parent node is root node, and children nodes are left node and a right node.
⦁ root.left points to a node left
⦁ root.right points to a node right.
Inside checkTree function you receive root as a parameter. This root is a instance of TreeNode which will look something like right and left can point to other TreeNodes as well.

 

Scenario 1:
So suppose if tree is something like this

root is 9, root.left would be node 4 and root.right would be node 5

root.left.val is equal to 4 and root.right.val is equal to 5 & root.val is 9

So if addition of both root.left.val & root.right.val is equal to root.val the return statement would return true else false.

So in this case it would return true as 4 + 5 is equals to 9

var checkTree = function(root) {
return root.left.val + root.right.val === root.val
};

 

Scenario 2:
So suppose if tree is something like this

// Definition for a binary tree node. 
function TreeNode(val, left, right) {
this.val = (val===undefined ? 0 : val) 
this.left = (left===undefined ? null : left) 
this.right = (right===undefined ? null : right)
}

root is 5, root.left would be node 1 and root.right would be node 3 root.left.val is equal to 1 and root.right.val is equal to 3 & root.val is 5
So if addition of both root.left.val & root.right.val is equal to root.val the return statement would return true else false.

So in this case it would return false as 1 + 3 is not equal to 5.

var checkTree = function(root) {
return root.left.val + root.right.val === root.val
};

 

Leave a comment