Checking for univalued Binary Search Tree in JavaScript

JavascriptWeb DevelopmentFront End Technology

Univalued Binary Search Tree

A binary search tree is univalued if every node in the tree has the same value.

Problem

We are required to write a JavaScript function that takes in the root of a BST and returns true if and only if the given tree is univalued, false otherwise.

For example, if the nodes of the tree are −

const input = [5, 5, 5, 3, 5, 6];

Then the output should be −

const output = false;

Example

The code for this will be −

 Live Demo

class Node{
   constructor(data) {
      this.data = data;
      this.left = null;
      this.right = null;
   };
};
class BinarySearchTree{
   constructor(){
      // root of a binary seach tree
      this.root = null;
   }
   insert(data){
      var newNode = new Node(data);
      if(this.root === null){
         this.root = newNode;
      }else{
         this.insertNode(this.root, newNode);
      };
   };
   insertNode(node, newNode){
      if(newNode.data < node.data){
         if(node.left === null){
            node.left = newNode;
         }else{
            this.insertNode(node.left, newNode);
         };
      } else {
         if(node.right === null){
            node.right = newNode;
         }else{
            this.insertNode(node.right,newNode);
         };
      };
   };
};
const BST = new BinarySearchTree();
BST.insert(5);
BST.insert(5);
BST.insert(5);
BST.insert(3);
BST.insert(5);
BST.insert(6);
const isUnivalued = (root) => {
   const helper = (node, prev) => {
      if (!node) {
         return true
      }
      if (node.data !== prev) {
         return false
      }
      let isLeftValid = true
      let isRightValid = true
      if (node.left) {
         isLeftValid = helper(node.left, prev)
      }
      if (isLeftValid && node.right) {
         isRightValid = helper(node.right, prev)
      }
      return isLeftValid && isRightValid
   }
   if (!root) {
      return true
   }
   return helper(root, root.data)
};
console.log(isUnivalued(BST.root));

Output

And the output in the console will be −

false
raja
Published on 09-Apr-2021 08:48:33
Advertisements