Discovering the height on the left and right sides within a Binary Search Tree

Is there a way to determine the length of the path from the root to the deepest node in the tree for both sides? I know that the maximum height of the tree can be found using the height() method as shown in the following code. Is there a method to find the heights of the left and right sides separately?

const inputString1 = `13
    25
    39
    12
    19
    9
    23
    55
    31
    60
    35
    41
    70
    90`;
    //left 3 right 5
    const inputLines1: string[] = inputString1.split("\n");
    let leftHeight = 0;
    let rightHeight = 0;
    let currentLine1: number = 0;
    function readLine1(): string {
      return inputLines1[currentLine1++];
    }
    
    class TreeNode1<T> {
      private _value: T;
      public getvalue(): T {
        return this._value;
      }
      public setvalue(v: T) {
        this._value = v;
      }
    
      private _left: TreeNode1<T>;
    
      public getleft(): TreeNode1<T> {
        return this._left;
      }
    
      public setleft(node: TreeNode1<T>) {
        this._left = node;
      }
    
      private _right: TreeNode1<T>;
    
      public getright(): TreeNode1<T> {
        return this._right;
      }
    
      public setright(node: TreeNode1<T>) {
        this._right = node;
      }
    
      constructor(value: T) {
        this._value = value;
        this._left = null as any;
        this._right = null as any;
      }
    }
    
    class BinarySearchTree1<T> {
      leftHeight:number=0;
      rightHeight:number=0;
      height() {
        return this._height(this._root);
      }
    
      _height(root?: TreeNode1<T>): any {
        if (!root || (root.getleft() == null && root.getright() == null)) {
          return 0;
        }
    
        return (
          1 + Math.max(this._height(root.getleft()), this._height(root.getright()))
        );
      }
    
      private _root: TreeNode1<T>;
      public getroot(): TreeNode1<T> {
        return this._root;
      }
    
      public setroot(v: TreeNode1<T>) {
        this._root = v;
      }
      constructor() {
        this._root = null as any;
      }
    
      addToTree(v: T): boolean | undefined {
        const newNode = new TreeNode1(v);
        if (this._root == null) {
          this._root = newNode;
          return true;
        } else {
          let currentNode = this.getroot();
          let traversing = true;
          while (traversing) {
            if (currentNode != null) {
              if (currentNode.getvalue() == newNode.getvalue()) {
                traversing = false;
                return false;
              } else if (currentNode.getvalue() > newNode.getvalue()) {
                if (currentNode.getleft() == null) {
                  currentNode.setleft(newNode);
                  traversing = false;
                  return true;
                } else {
                  currentNode = currentNode.getleft();
                }
              } else {
                if (currentNode.getright() == null) {
                  currentNode.setright(newNode);
                  traversing = false;
                  return true;
                } else {
                  currentNode = currentNode.getright();
                }
              }
            }
          }
        }
      }
    
      BFS(): T[] {
        let queue = new Array<TreeNode1<T>>();
        let visited = new Array<T>();
        queue.push(this._root);
        while (queue.length != 0) {
          let currentNode = queue.shift();
          if (currentNode !== null) {
            visited.push(currentNode!!.getvalue());
          }
    
          if (currentNode !== null) {
            if (currentNode!!.getleft() !== null)
              queue.push(currentNode!!.getleft());
            if (currentNode!!.getright !== null)
              queue.push(currentNode!!.getright());
          }
        }
        return visited;
      }
    }
    
    function main1() {
      let myBST = new BinarySearchTree1<number>();
      for (let i = 1; i < inputLines1.length; i++) {
        myBST.addToTree(Number(inputLines1[i]));
      }
      console.log("BFS: " + myBST.BFS(), myBST.height());
      console.log(leftHeight, rightHeight);
    }
    
    main1();

Answer №1

Initially, it's important to note that the height of a tree with no nodes is considered to be -1, according to Wikipedia:

Traditionally, an empty tree (a tree without any nodes, if permitted) has a height of −1.

Therefore, your code for the height method needs to be adjusted as follows:

  _height(root?: TreeNode1<T>): number {
    if (!root) {
      return -1;
    }
    return (
      1 + Math.max(this._height(root.getleft()), this._height(root.getright()))
    );
  }

You should then eliminate the leftHeight and rightHeight properties and refactor them into methods:

  leftHeight(): number {
    if (!this._root) {
      return -2;
    }
    return this._height(this._root.getleft());
  }
  rightHeight(): number {
    if (!this._root) {
      return -2;
    }
    return this._height(this._root.getright());
  }

...and ensure to invoke them within your primary function.

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

Define variables using specific class components only

Consider a scenario where we define a class as follows: class House { street: string; pools: number; helicopterLandingPlace: boolean; } Now, I have created a service to update my house. putHouse(house: House) { // some put request } How ...

Transform the dynamic JSON format into a key-value pair structure with nested children nodes

Looking to convert a dynamic JSON structure into a tree node: { "video": { "width": 1920, "height": 1080, "video_codec": "H264", "CBR": "4337025", "frame_rate& ...

Creating custom designs for a HTML button using CSS

Within an HTML form, there are two buttons set up as follows: <button kmdPrimaryButton size="mini" (click)="clickSection('table')">Table View</button> <button kmdPrimaryButton size="mini" (click)=&quo ...

Unable to find '.file.scss' in the directory '../pages'

I am currently in the process of migrating my Ionic 3 app to version 4. However, I have encountered an issue where some pages are not recognizing the SCSS file from the TypeScript component. @Component({ selector: 'car-id', templateUrl: &apo ...

Error: The Class object cannot be found in Object(...)(...)

I've been encountering a TypeError while trying to implement this angular code. The error seems to be generated around Class({constructor: function() {}}), but I'm not exactly sure why. Any help on this would be greatly appreciated. import "hell ...

Unable to initialize metro server due to the error "attachToServer is not a valid function"

After following the instructions in the original documentation, I executed npx react-native init AwesomeProject without making any changes. However, when I try to run npx react-native start or yarn start, I encounter an error stating that attachToServer i ...

What is the process for assigning a serial number to each row in the MUI DataGrid?

Initially, the server is accessed to retrieve some data. After that, additional data is added. While the data does not contain an ID, the form must still display a serial number. const columns: GridColDef[] = [ { field: 'id' ...

Centralized MUI design for varying screen dimensions

I am struggling to perfectly center my modal box in the middle of the screen. The problem arises when the screen size changes, causing the box to be misaligned. I attempted using top:50% and left: 50%, but this did not effectively center the box. center ...

Utilizing discriminated unions in conjunction with classes: A step-by-step guide

I'm having an issue converting a discriminated union into a string. The union comprises two interfaces. When I use the function with a simple object that matches one of the interfaces, I get the desired output. However, if I use a class that implement ...

What is the best way to transform a synchronous function call into an observable?

Is there a conventional method or developer in RxJS 6 library that can transform a function call into an observable, as shown below? const liftFun = fun => { try { return of(fun()) } catch (err) { return throwError(err) } ...

What could be causing this error for my NPM module in a .NET Core project using Typescript?

My Typescript configuration seems to be causing some issues, even though everything works fine without TS. Could the problem lie in my .d.ts file? And do I really need it for webpack? I have a basic NPM module: index.js: var MyMathTS = function(a, b){ ...

Error Message: The specified HTML element already contains two instances of the WebViewer, leading to a conflict in PDFTron React TypeScript Next

Having some trouble using pdftron with my docx editor. I can use the editor fine, but keep encountering an error like the one shown below: https://i.stack.imgur.com/OnJxE.png https://i.stack.imgur.com/l9Oxt.png Here is a snippet of my code: wordeditor.t ...

The FormData object appears to be blank, even though it was supposed to be populated when attempting to send a PDF file using a multipart FormData POST request in Cypress

I am attempting to send a PDF file as a POST request. The API supports the use of @RequestPart and @RequestParam: @RequestPart("file") MultipartFile file; @RequestParam(value = "document-types", required = false) Set<String> documentTypes; My appro ...

Tips for resolving the issue when Chrome is able to load the page but Postman cannot find it

I'm encountering a perplexing situation that is entirely new to me and difficult to comprehend. I find myself unable to decipher what exactly I am witnessing, leading to uncertainty about why it is occurring, not to mention the challenge of determinin ...

Leverage the properties of a class to serve as choices for a method's input

I am working on a class called Snackbar that consists of various properties and methods. Here is an example: export class SnackbarComponent { optionA: number; option2: string; method1(){} } My goal is to include the properties as keys in the option ...

Restricting a checkbox to a maximum of 5 checkmarks

In a multi-column table, each column is represented by a checkmark. I want to limit the ability to tick a checkmark to only 5 checkmarks. Here is the code that has been implemented: <tbody> <ng-container *ngFor="let col of testData" ...

What sets my project apart from the rest that makes TypeScript definition files unnecessary?

Utilizing .js libraries in my .ts project works seamlessly, with no issues arising. I have not utilized any *.d.ts files in my project at all. Could someone please explain how this functionality is achievable? ...

The property is not found within the type, yet the property does indeed exist

I'm baffled by the error being thrown by TypeScript interface SendMessageAction { type: 1; } interface DeleteMessageAction { type: 2; idBlock:string; } type ChatActionTypes = SendMessageAction | DeleteMessageAction; const CounterReduc ...

"Troubleshooting a case where mongoDB's updateOne function is

I am in the process of removing certain references to objects within different sections (section1, section2, section3, others) in each file. Sample Document: { "_id": "64a3268474aa29e72b40c521", "name": "Test", ...

Issues encountered with Nextjs 13.4 and Next-Auth 4.2 regarding the signIn("credentials", { }); functionality not functioning as expected

When using next-auth credentials in my current project, I encountered an issue with the signIn() function from next-auth/react. It appears that the redirection to the admin page persists regardless of whether the login details are correct or not. {error: n ...