0
0
DSA Javascriptprogramming~30 mins

Validate if Tree is BST in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Validate if Tree is BST
📖 Scenario: You are working with a simple binary tree structure in JavaScript. Your task is to check if this tree follows the rules of a Binary Search Tree (BST).A BST is a tree where for every node, all values in the left subtree are smaller, and all values in the right subtree are larger.
🎯 Goal: Build a program that creates a binary tree, sets up a helper function to check BST rules, and then prints whether the tree is a valid BST or not.
📋 What You'll Learn
Create a binary tree with exact nodes and values
Add a helper function to validate BST rules
Use recursion to check the tree
Print 'true' if the tree is a BST, otherwise 'false'
💡 Why This Matters
🌍 Real World
Checking if a tree is a BST is important in databases and search algorithms where data needs to be organized for fast lookup.
💼 Career
Understanding BST validation helps in roles like software development and data engineering where tree data structures are common.
Progress0 / 4 steps
1
Create the binary tree nodes
Create a class called Node with a constructor that takes value, left, and right. Then create a tree with root node value 10, left child 5, and right child 15. Assign the root node to a variable called root.
DSA Javascript
Hint

Start by defining a Node class with a constructor. Then create the root node with value 10, and its left and right children with values 5 and 15.

2
Add helper function to check BST validity
Create a function called isBST that takes a node, a min value, and a max value. Initialize min and max to -Infinity and Infinity respectively when first called. The function should return false if the node value is not between min and max. Otherwise, recursively check the left subtree with updated max and the right subtree with updated min. Return true if all checks pass.
DSA Javascript
Hint

Use recursion to check if each node's value fits between min and max. Update these limits as you go down the tree.

3
Call the helper function with the root node
Create a variable called result and assign it the value returned by calling isBST with the root node.
DSA Javascript
Hint

Call isBST with the root node and store the answer in result.

4
Print the result
Print the value of the variable result using console.log.
DSA Javascript
Hint

Use console.log(result) to show if the tree is a BST.