Code in Javascript that performs a check for pre-order traversal

I’m interested in writing a preorder traversal code in Java for JavaScript. I’ve been practicing this question on geeksforgeeks:

Check if a given array can represent Preorder Traversal of Binary Search Tree

This is the algorithm they provided:

1) Create an empty stack.
2) Initialize root as INT_MIN.
3) Do following for every element pre[i]
     a) If pre[i] is smaller than current root, return false.
     b) Keep removing elements from stack while pre[i] is greater
        then stack top. Make the last removed item as new root (to
        be compared next).
        At this point, pre[i] is greater than the removed root
        (That is why if we see a smaller element in step a), we 
        return false)
     c) push pre[i] to stack (All elements in stack are in decreasing
        order) 

I'm struggling to understand the above algorithm because I’m not sure what an empty stack is (possibly an empty array?), INT_MIN?

If an empty stack is an empty array, what does this statement mean?

Keep removing elements from stack while pre[i] is greater
than stack top. Make the last removed item the new root (to
be compared next).

In summary, I've tried to come up with an algorithm but need help making it more readable since I only know how to code in Javascript.

Could you assist me in improving the readability of the algorithm for the above code?

Answer №1

responding to your inquiries:

  1. When referring to INT_MIN, the authors are indicating the smallest possible integer value, ensuring that any other number will be larger than INT_MIN. In JavaScript, you can use -Infinity for comparisons as it is considered smaller than any other numerical value. While mathematical operations cannot be performed on -Infinity, it is not necessary in this context.
  2. A stack is a data structure similar to an array that allows elements to be added on top of each other and removed from the top, returning the most recently added element. To implement a stack in JavaScript, you can either 1. create a wrapper around an array with methods like .push, .pop, and
    .peek</code, or 2. simply use an array and treat it as a stack. The latter option is more straightforward in this scenario.</li>
    <li>Regarding the question "<code>If empty stack is represented by an empty array, then what does this statement mean?
    ", initially, the stack is empty. However, as you progress through the example, items are added to the stack, and there is a condition to check if the stack remains non-empty when reaching this particular statement.

.

const canRepresentBST = (pre) => {
  const stack = []
  let root = -Infinity

  for (let i = 0; i < pre.length; i++) {
    if (pre[i] < root) {
      return false
    }
    while (stack.length && stack[stack.length - 1] < pre[i]) {
      root = stack.pop()
    }
    stack.push(pre[i])
  }
  return true
}

const pre1 = [40,30,35,80,100]
console.log(canRepresentBST(pre1))
const pre2 = [40,30,35,20,80,100]
console.log(canRepresentBST(pre2))

The purpose of this algorithm is to determine whether a given array of numbers (pre) represents a valid preorder traversal of a binary search tree.

Answer №2

After reviewing your example, I successfully converted the java code to JavaScript.

const isBST = (preorder) => {
  let root = Number.MIN_SAFE_INTEGER
  let stack = []
  
  for (let i = 0; i < preorder.length; i++) {
    if (preorder[i] < root) {
      return false
    }
    
    while (stack.length > 0 && stack[stack.length-1] < preorder[i]) {
      root = stack.pop()
    }

    stack.push(preorder[i])
  }

  return true
}

let preorder1 = [40, 30, 35, 80, 100]
let preorder2 = [40, 30, 35, 20, 80, 100]

console.log(isBST(preorder1) ? 'true' : 'false')
console.log(isBST(preorder2) ? 'true' : 'false')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using ngFor directive to iterate through nested objects in Angular

Receiving data from the server: { "12312412": { "id": "12312412", "something": { "54332": { "id": "54332", "nextNode": { "65474&q ...

Creating a JSX syntax for a simulated component and ensuring it is fully typed with TypeScript

Looking for some innovative ideas on how to approach this challenge. I have a test helper utils with added types: import { jest } from '@jest/globals' import React from 'react' // https://learn.reactnativeschool.com/courses/781007/lect ...

Creating a stacked chart in Angular using chart.js with JSON array of objects values

I am currently working on implementing a stacked chart using chart.js, and I have encountered some challenges: I am struggling to display currency values in the correct format on the chart (the height of the bar is not visible when passing amounts). How c ...

What causes my React app menu to unexpectedly open while simply updating the state without any CSS modifications?

In the Header component, there is a button that triggers the toggleNav function in context.js when clicked. This function changes the state of isNavOpen from false to true, resulting in the opening of the navigation. Surprisingly, there doesn't appear ...

Failure in rendering components with React and ElectronThe issue of rendering components with

As a newbie to the world of React and Electron, I have been experimenting with separating my components into different JSX files and importing them to render in div tags within my index page for an Electron app. However, I'm facing some confusion as i ...

Preventing CORS problems when a web application imports JavaScript modules from different domains

Currently, I am in the process of developing a web application using NodeJS. The application is divided into a back-end responsible for handling database queries with MongoDB, and a front end built on a Node-based web server that utilizes interactjs alongs ...

Accessing information from JSON files using AJAX

I'm currently working on loading data from a JSON file using AJAX. The file I'm referencing is external-file.json. Within the code snippet provided, there are other unrelated sections. I'm encountering an issue within the getViaAjax function ...

Sending the factory's response back to the controller in AngularJS

I operate a factory that uses an api call to request user data: angular.module('MyApp') .factory('UserApi', function($auth,Account){ return { getProfile: function() { Account.get ...

Transform JSON structure (Group data)

Here is the JSON object I am working with: [{ "name" : "cat", "value" : 17, "group" : "animal", }, { "name" : "dog", "value" : 6, "group" : "animal", }, { "name" : "snak", "value" : 2, "group" : "animal", }, { "na ...

What is the best method for ensuring a user remains logged in even after their access token expires, requiring them to log in again to resume their normal

Currently utilizing the Nuxt-axios module alongside a proxy. Implemented common error handling code in Plugins/axios.js export default function({ $axios, __isRetryRequest, store, app, redirect , payload , next}) { $axios.onRequest(config => { i ...

Use ag-Grid to customize your column headers with checkboxes, allowing you to easily select or deselect all items in that column. This feature is not limited to

In my experience with ag-grid, I often find myself needing to customize the first column header to include a checkbox. This allows me to easily perform actions such as selecting all or deselecting all rows in the grid. It's important to note that this ...

"Using conditional statements to check for specific value ranges and properly handling cases where the result is undefined

Currently, I am working on a function that prompts the user to input a number and then displays a calculated score after they click a button. The score is based on the value entered by the user. While constructing this feature, I have pondered whether IF ...

Modify the class of the focused element exclusively in Angular 2

I'm working on a project that involves several buttons and div elements. Currently, the divs are hidden, but I want to be able to reveal a specific div when its corresponding button is clicked. For example: If you click the first button, only the fir ...

Trouble with integrating HTML5 canvas from an external JavaScript file

Having trouble with storing canvas js in an external file. If the javascript responsible for drawing on the canvas is included in the html header, then the rectangle is displayed correctly. Here is the working html (javascript in html header): <!DOCT ...

In the strict mode tree, a reference named "grid" has been discovered

I encountered the following warning in the console: Warning: A string ref, "grid", has been found within a strict mode tree. String refs can potentially lead to bugs and should be avoided. It is recommended to use useRef() or createRef() instead. T ...

Implementing a more efficient method for incorporating UUIDs into loggers

------------system1.ts user.on('dataReceived',function(data){ uniqueId=generateUniqueId(); system2.processData(uniqueId,data); }); ------System2.ts function processData(u ...

A guide on retrieving the selected option from a dropdown menu with React Material UI

Utilizing Material UI React, I am constructing a dropdown menu containing various options. My concern is: if I choose two options from different dropdowns within the menu, how can I intercept or store which option was selected? Below is a snippet of my co ...

What is the best way to store multiple forms in a single request using React?

Is there a more efficient way for me to save multiple forms in multiple child components from the parent component using just one API request? I have attempted to utilize Context and reducer, which did work. However, I am unsure if this is the best approa ...

Location of chat icon in Dialogflow messenger

After successfully embedding the Dialogflow messenger in my website, I noticed that in mobile view, the chat icon is blocking the bottom navigation bar. You can refer to the screenshot here. Is there a way to reposition the chat icon higher on the page? I ...

Oops! There seems to be an issue with an invalid character in the literal true value while making a POST request to the API with JSON data. The expected character should be

Can anyone help me solve an issue I am facing while trying to use the POST method to insert data using JSON in JS code? When I attempt the transformation, I receive an error message stating: "ERROR: invalid character ' ' in literal true (e ...