Traversal of a binary tree in the order of visitation specified by the In

My task was to create a function that traverses a binary tree and returns an array of all its values in inorder. The code provided is:

interface BinTree {
root: number;
left?: BinTree;
right?: BinTree;
 };
 const TreeInArray =(t:BinTree):number[] =>{
       let list = new Array<number>(); 
        if (t.left!=undefined) { 
            list = list.concat(TreePreArray(t.left))  
        }
       list.push(t.root)
       if (t.right!=undefined){ 
          list = list.concat(TreePreArray(t.right))
        }
    return list
 }
 let bn1 : BinTree = { // DOES NOT PASS TYPE CHECKING
 root: 1,
 left: { root: 2 ,
    left:{root:4 },right:{root:5 } },
 right: { root: 3}
 }
 console.log((TreeInArray(bn1)));

The current output is

[ 2, 4, 5, 1, 3 ]

However, I was hoping for an output like this

[4, 2, 5, 1, 3]

I'm trying to understand why the output differs from my expectations. Any insights?

Answer №1

You have mistakenly invoked the pre-order version instead of the in-order version recursively:

const ArrayFromTree = (t: BinaryTreeNode): number[] => {
    let result = new Array<number>();
    if (t.left !== undefined) {
        result = result.concat(ArrayFromTree(t.left))
    }
    result.push(t.value)
    if (t.right !== undefined) {
        result = result.concat(ArrayFromTree(t.right))
    }
    return result
}

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

Is there a built-in constant in the Angular framework that automatically resolves a promise as soon as it

I'm facing a situation where I have code that checks a conditional statement to decide if an asynchronous call should be made. If the condition is not met, the call is skipped. However, I still need to perform some final action regardless of whether t ...

Sending an HTTP request from within an Express/Node.js application

I am currently in the process of setting up an express service for a program I am developing. The goal is to interact with an external API, retrieve the data, and store it in a MongoDB database that I have already set up. While this task may seem straight ...

Querying MongoDB with a JavaScript file for formatting datetime values

I am utilizing mongodb3.0.5 and my database collection appears as follows: { "_id" : "xxxxxxxxxxxxxxx", "SchoolId" : 1, "ActivationTimestamp" : ISODate("2015-09-22T13:01:58.000Z"), "PersonDetails" : [ { "Name" : "John" ...

Enhance user experience by implementing a feature in AngularJS that highlights anchor

As I am in the process of developing a chat application using Angular, I have encountered an issue with switching between views. One view, named 'chat.html', displays the list of available users while another view, 'chatMessages.html', ...

How can a .NET Core Rest API emit a stream to be consumed in Angular as an observable?

I'm interested in creating a dynamic page that continuously fetches data from the backend, allowing the data set to grow over time until the backend indicates completion (which may never happen). Similar to the concept discussed in this article, but u ...

Navigating React Router: Updating the page on back button press

Looking for a solution to a persistent issue. Despite various attempts and exhaustive research, the problem remains unresolved. Here's the situation: Within my React-Router-Dom setup, there is a parent component featuring a logo that remains fixed an ...

Guide to dynamically inserting an audio file into a div with jQuery

I am looking to dynamically insert an audio file. Below are the declared tags: <div> <audio id="myaudio"> </audio> </div> Now, I am trying to add the source dynamically. Can anyone help me with how to add it to the div or audi ...

Issue with authentication when accessing Google Video API

I'm attempting to utilize the Google API provided: I have downloaded the Sample Project and followed these steps: 1) Navigate to the Project Folder named API Video 2) Run npm install 3) Set GCLOUD_PROJECT = neorisvideo 4) Download Json from the C ...

Tips for storing a JavaScript variable or logging it to a file

Currently working with node, I have a script that requests data from an API and formats it into JSON required for dynamo. Each day generates around 23000 records which I am trying to save on my hard drive. Could someone advise me on how to save the conte ...

Need for input

I am working on organizing my routes in a separate file from app.js. The login route requires access to a Firebase instance. routes/auth.js var express = require('express'); var router = express.Router(); module.exports = function(firebase) { ...

Struggling to interpret JSON data from an AJAX call using jQuery in a Python/Flask application

Currently, I am attempting to analyze a POST request sent via AJAX using jQuery in a python script. The structure of the request is as follows: request.js function get_form_data($form){ var unindexed_array = $form.serializeArray(); var indexed_ar ...

Strategies for integrating user data into Vue components within Laravel

I've successfully logged my user data in the console, but when I try to display the data on Contalist page, nothing is returned. I'm new to using Vue and need help implementing it into my projects. Below are my PHP controller and Vue component fi ...

Transform a <td> into a table-row (<tr>) nested within a parent <tr> inside an umbrella structure

Similar questions have been asked in the past, but I still haven't found a solution to my specific inquiry. Here it is: I have a table that needs to be sortable using a JavaScript plugin like ListJS. The key requirement is that I must have only one & ...

Load various information retrieved from an HTTP API into a SQLite database

I am currently working on an Ionic2 project that requires users to log in before gaining access to the system. Once the login is successful, I need to post their username to another API to retrieve a list of all entries made by them. The challenge I am fac ...

Securing Routes with Firebase User Authentication in ReactJS

Currently, I am encountering an issue with the auth.onAuthStateChanged function in my Firebase user authentication service integrated with ReactJS. The function fires after the component has already been rendered, causing problems with redirecting users to ...

Guide on capturing every error thrown in a Vue.JS single-page application

As I develop a web application, my goal is to effectively capture any errors that may occur throughout the entire Vue.js web app. Although I investigated the errorHandler, I discovered that it only catches errors during rendering or watching processes. Th ...

Tracking the frequency of text values that have been clicked on

Feeling uncertain about the best direction to take. In a table of unknown length, the first column consists of clickable links, while the second column contains corresponding text. The number of rows in this table is variable and depends on search resul ...

Encountering difficulty in establishing a global variable within the subscribe function

I am looking to store the service response in a variable for use in my view. The TypeScript file I am working with is shown below: The MenuService is a custom service that includes a function called getMenus() to fetch all menus from the database. import ...

Coordinated Universal Time on the Website

I am currently developing a website that will be exclusively accessible through the intranet, but it targets users across Australia. Recently, I have been instructed to explore the idea of incorporating UTC time on the site. I am contemplating how I can i ...

Triggering JSON schema validation event in React's Monaco Editor

I am interested in implementing custom JSON schema validation in my Monaco editor setup. Here is the current configuration: <MonacoEditor language="json" value={jsonValue} editorWillMount={(monaco) => { monaco.languages.json.jsonD ...