Categories
binary trees data structures javascript

Data Structures Problem – Checking for Children Sum Property in a given Binary Tree 🌳

✨Data Structures Problem – Checking for Children Sum Property in a given Binary Tree 🌳

 

Hey guys 👋🏻,

I just released a new video on solving an interview problem :

Checking for Children Sum Property in a given Binary Tree

In this video, we will solve the problem of checking whether the given binary tree satisfies the children sum property or not.
We will first understand the approach that we will be taking to solve this problem and then we will write the code for the same problem together. Once we are done with the implementation, we will do a quick dry run for the code to understand and make complete sense of the output that we get. Here is the code from that video : 

// Children Sum Property in a binary tree

// We need the class for a node first
class Node {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}
let rootNode;

function isChildrenSumPropertySatisfied(node) {
  let leftChildData = 0;
  let rightChildData = 0;

  if(node === null || (node.left === null && node.right === null)) {
    return true;
  }else {
    leftChildData = node.left !== null *
  }
}

function isChildrenSumPropertySatisfied(node) {

  let leftChildData = 0;
  let rightChildData = 0;

  if (node == null || (node.left == null && node.right == null)) {
    return true;
  } else {
    if (node.left != null) {
      leftChildData = node.left.data;
    }
    if (node.right != null) {
      rightChildData = node.right.data;
    }

    if ((node.data == rightChildData + leftChildData) &&
      (isChildrenSumPropertySatisfied(node.left) != false)
      && (isChildrenSumPropertySatisfied(node.right) != false)) {
      return true;
    }else {
      return false;
    }
  }

}
const root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.right = new Node(2);

if (isChildrenSumPropertySatisfied(root) != 0) {
  console.log('The given tree satisfies the children sum property');
} else {
  console.log('The given tree does not satisfies the children sum property.');
}

So this is it for this article. Thanks for reading.
Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text