Today I have solved the problem in javascript

 A ternary search tree is a trie-like data structure where each node may have up to three children. Here is an example which represents the words code, cob, be, ax, war, and we.


       c

    /  |  \

   b   o   w

 / |   |   |

a  e   d   a

|    / |   | \ 

x   b  e   r  e

The tree is structured according to the following rules:


left child nodes link to words lexicographically earlier than the parent prefix

right child nodes link to words lexicographically later than the parent prefix

middle child nodes continue the current word

For instance, since code is the first word inserted in the tree, and cob lexicographically precedes cod, cob is represented as a left child extending from cod.


Implement insertion and search functions for a ternary search tree.

const tree = { root: null };

const words = ["code", "cob", "be", "ax", "war", "we"];


words.forEach((word) => insert(tree, word));

function createNode(val) {

  return { val, left: null, middle: null, right: null, isEnd: false };

}


function insert(tree, word, node = tree) {

  if (!tree.root) {

    tree.root = createNode(word[0]);

    insert(tree, word.slice(1), tree.root);

  } else {

    const char = word[0];

    if (char < node.val) {

      if (!node.left) node.left = createNode(char);

      insert(tree, word, node.left);

    } else if (char > node.val) {

      if (!node.right) node.right = createNode(char);

      insert(tree, word, node.right);

    } else {

      if (word.length > 1) {

        if (!node.middle) node.middle = createNode(word[1]);

        insert(tree, word.slice(1), node.middle);

      } else {

        node.isEnd = true;

      }

    }

  }

}


function search(tree, word, node = tree.root) {

  if (!node) return false;


  const char = word[0];

  if (char < node.val) {

    return search(tree, word, node.left);

  } else if (char > node.val) {

    return search(tree, word, node.right);

  } else {

    if (word.length > 1) {

      return search(tree, word.slice(1), node.middle);

    } else {

      return node.isEnd;

    }

  }

}

console.log(search(tree, "code")); 

console.log(search(tree, "cob"));

console.log(search(tree, "bat")); 

Output:

false
false
false



Comments

Popular posts from this blog

Building a Full-Stack Student Management System with React.js and NestJS

Today I have solved the problem in javascript

Today I have solved problem in javascript