Embark on a journey through a preorder traversal of a Binary Tree using TypeScript

Hello! I've been tasked with creating a function that iterates over a binary tree and returns all its values in pre-order. Here is the code snippet:

interface BinTree {
    root: number;
    left?: BinTree;
    right?: BinTree;
};
const TreePreArray =(t:BinTree):number[] => {
    let list = new Array<number>();
    if (t == undefined) {return list }
    else {
        list.push(t.root)
        list.concat(TreePreArray(t.left))
        list.concat(TreePreArray(t.right))
    }
    return list
}
let bn : BinTree = {
    root: 1,
    left: { root: 2 },
    right: { root: 3 }
}
console.log((TreePreArray(bn)));

However, the output only shows [1] instead of [1,2,3]. I found inspiration from this link Recursive Tree Traversal Method With Return Type Array and decided to implement it in TypeScript.

Answer №1

In order to properly utilize the result of the concat function, you must either push the result or assign it to a variable. Failing to do so means that you will not be able to access the results of traversing the different branches.

You have two options:

list = list.concat(TreePreArray(t.left))
list = list.concat(TreePreArray(t.right))

or

list.push(...TreePreArray(t.left))
list.push(...TreePreArray(t.right))

Answer №2

An excellent example of utilizing iterators is shown here:

 function* startFromLeft({left, right, root} : BinaryTree) {
  yield root; 
  if(left) yield* startFromLeft(left); 
  if(right) yield* startFromLeft(right); 
 }

To convert the result to an array, simply use:

 [...startFromLeft(tree)]

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

Leveraging grunt-develop

I have recently developed a basic NodeJS + Express application that runs smoothly when I use the command node app.js. However, my current task is to incorporate grunt-develop into my project. Here is how I configured it: grunt.initConfig({ develop: { ...

Is there a way to customize the primary column in Material-table?

I am utilizing the Material-table and I am in need of rearranging the column index to be at the end of the table as the default position for this column (actions) is at the beginning. Here is the code snippet for the table: <MaterialTable title=" ...

Using AJAX to populate a dropdown menu in a CodeIgniter application

I'm having an issue with using AJAX to populate a dropdown option. Here is the JavaScript code I am using: <script type="text/javascript"> $(document).ready(function(){ $("#sepatu").click(function(e){ e.preventDefault() ...

Ways to update the div's color according to a specific value

Below are the scripts and styles that were implemented: <script src="angular.min.js"></script> <style> .greater { color:#D7E3BF; background-color:#D7E3BF; } .less { color:#E5B9B5; background-co ...

Having trouble with implementing both filter and infinite scroll simultaneously in an Ionic list?

I've encountered an issue with my ionic hybrid app related to angularjs filters. The code snippet below showcases the problem: <input type="search" placeholder="Search personalities" ng-model="name" ng-change='alert("changed!")&apo ...

Retrieve tabs according to the value selected in the dropdown menu

When a value is selected from a dropdown with options 1 to 5, I want to display a corresponding number of tabs. Below is the HTML code for the select box: <select id="Week" name="Week"> <option value="1">1</option> <option val ...

Retrieve the item that is contained within a separate item within the original

Is there a way to access the Photos object in my code? I attempted to use {{ item.image.Photos[0].image }} but it was unsuccessful https://i.stack.imgur.com/IGC2c.png Looking for Assistance with TypeScript listHotelPhotos( hotel_id ){ let loader = t ...

Explore an object to locate an element along with its parent

Here is an example of an object: $scope.categories = [ { value: 'One', id: 1, childs: [ { value: 'Two', id : 2, childs: [ { v ...

Experiencing a type error within Redux in a React Native project utilizing TypeScript

I am currently working on implementing a feature to store the boolean value of whether a phone number is verified or not. Within my login component: await dispatch(setOTPVerified(data.is_phone_verified)); Action.tsx: export const OTP_VERIFIED = 'OTP ...

A step-by-step guide on accessing an expressjs endpoint from a static html file using Vercel

I am working on a basic app that consists of one server named /api/index.js and one file called index.html located at the root. In the index.js file, there is a route defined as app.get("/api/mystuff", () => {...}) The index.html file makes a request ...

Utilize THREE.js to control the camera with a button click

I'm looking to add separate buttons on my website, where each button triggers the camera to move to a different position within the scene. How can I achieve this? Currently, I have set up a system where pressing a button leads to a sequence of predefi ...

What is a clever way to monitor the completion of a forEach loop using promises?

I'm new to promises and I'm attempting to use them for the first time. After the completion of the forEach loop, I want to call another function for additional processing. However, when using forEach, the function insertIDBEvents is only printed ...

Is there a way to convert this JSON object into HTML table code?

I've been working on tweaking a code snippet I came across, but I'm struggling to get it to function the way I desire. Here is the current Javascript code: function JsonUtil() { /** * Given an object, * return its type as a string. ...

Ways to retrieve the identifier of a specific element within an array

After successfully retrieving an array of items from my database using PHP as the backend language, I managed to display them correctly in my Ionic view. However, when I attempted to log the id of each item in order to use it for other tasks, it consistent ...

What is the most reliable way to create an array ensuring that all potential values come from a specific dictionary?

I am seeking a method to define the testArray so that only keys from the example dictionary can be inserted into the array. enum example { key1 = 'A', key2 = 2, key3 = '3', }; const testArray: ?? = [example.key1, example.ke ...

What is the best approach for dynamically appending new elements to a JSON array using PHP?

I am facing an issue with the JSON below: [{"username":"User1","password":"Password"}, {"username":"User5","password":"passWord"},] The above JSON is generated using the PHP code snippet mentioned below: <?php $username = $_POST["username"]; ?>&l ...

Can JavaScript trigger an alert based on a CSS value?

Hello, I am facing an issue. I have created a blue box using HTML/CSS and now I want to use JavaScript to display an alert with the name of the color when the box is clicked. Below is my code: var clr = document.getElementById("box").style.background ...

What is the best way to apply the addClass method to a list element

I've been searching for a solution to this issue for some time now, and while I believed my code was correct, it doesn't appear to be functioning as expected. HTML <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js ...

Dealing with errors in Next.js api: Best practices

When it comes to organizing code in Next.js api handlers, what is the most effective practice? In a video I watched, the presenter suggested placing all REST routes in two specific files: pages/api/users/index.ts would manage operations that do not requ ...

What can you do to prevent a div from taking up the entire page if its height is not specified?

Currently, I am experiencing an issue with my layout. I have a hidden div with a fixed position that becomes visible when a button on the page is clicked. Inside this div, there is a table of buttons for the user to choose from. The problem arises when I ...