Find the predecessors of a specific node within a tree structure

Looking for help with my tree structure. I am trying to retrieve all ancestors of a specific node in the tree, where each node can have multiple children and each child can also be a parent.

https://i.sstatic.net/cPqSM.png

Below is the code I've written to achieve this, but it consistently returns undefined. Any suggestions or advice would be greatly appreciated.

  getAncestors(nodeId: number, ancestors: number[] = []): number[] {
    if (this.nodeId === nodeId) {
      return ancestors;
    }
    
    if (this.children.length > 0) {
      ancestors.push(this.nodeId);
    }
    
    for (const child of this.children) {
      child.getAncestors(nodeId, ancestors);
    }

    return ancestors;
  }

Answer №1

Just by reading the following sentence, it should raise a major concern:

child.getAncestors(nodeId, ancestors);

If I have to ask my children who their parents are every time someone inquires about my ancestry, then the process is not only highly inefficient but also runs the risk of encountering an infinite loop. It's best to refrain from involving children in this function altogether.

A more suitable solution would largely depend on the overall structure of the node class. For instance, if each node has direct access to the root, we could start our search from the root and trace back to the original node while keeping track of all traversed nodes along the way. However, this approach might become convoluted.

An alternative, simpler option would be to maintain a record of all ancestors as each node gets created. Take a file system for example, where an absolute path is essential for accessing any file. Updating this list of ancestors becomes necessary if frequent node reorganization and movement are anticipated.

If nodes had direct access to their parents, accomplishing this task could be achieved through a straightforward while loop and a pointer:

ancestors = [];
nodePtr = this;
while (nodePtr !== root) {
    nodePtr = nodePtr.parent();
    ancestors.push(nodePtr);
}
ancestors.push(root);

Answer №2

I recently tackled a similar issue by utilizing a recursive function.

The recursive function must return a boolean value to indicate whether the node has been found, serving as the signal for adding ancestors. Additionally, it should include an array list in the parameter list to store the ancestors. For further details, you can check out the following link: https://www.geeksforgeeks.org/print-ancestors-of-a-given-node-in-binary-tree/

// JavaScript program to print ancestors of given node
     
    class Node
    {
        constructor(item) {
              this.data = item;
            this.left = null;
            this.right = null;
            this.nextRight = null;
        }
    }
     
    let root;
    
    /* If target is present in tree, then prints the ancestors
       and returns true, otherwise returns false. */
    function printAncestors(node, target)
    {
         /* base cases */
        if (node == null)
            return false;
    
        if (node.data == target)
            return true;
    
        /* If target is present in either left or right subtree
           of this node, then print this node */
        if (printAncestors(node.left, target)
                || printAncestors(node.right, target))
        {
            document.write(node.data + " ");
            return true;
        }
    
        /* Else return false */
        return false;
    }
     
    /* Construct the following binary tree
                    1
                  /   \
                 2     3
                /  \
               4    5
              /
             7
          */
    root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.left.right = new Node(5);
    root.left.left.left = new Node(7);
 
    printAncestors(root, 7);

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

Customize YouTube iframe styles in Angular 4+ with TypeScript

Has anyone been successful in overriding the style of an embedded YouTube iframe using Angular 4+ with TypeScript? I've attempted to override a CSS class of the embed iframe, but have not had any luck. Here is the URL to YouTube's stylesheet: ...

I made a mistake with my git repository. Should I try to fix it or just start fresh?

After spending months learning web development, I recently completed my first project. Unfortunately, right before deployment, I made a mistake with my backend git tree. I attempted to resolve the issue using suggestions from other resources, but none of ...

The state of the Toggle Button in Material UI

I am currently working with Material UI's ToggleButton and ToggleButtonGroup components. However, I'm facing an issue where the ToggleButton remains highlighted even after clicking on another button in the group. While the buttons are registering ...

What is the best way to insert a newline in a shell_exec command in PHP

I need assistance with executing a node.js file using PHP. My goal is to achieve the following in PHP: C:proj> node main.js text="This is some text. >> some more text in next line" This is my PHP script: shell_exec('node C:\pr ...

What are some solutions for managing SubPixel Handling issues on an iPhone?

Issue: I am currently in the process of developing a PhoneGap/Cordova app for both iOS and Android using jQuery Mobile. To incorporate a calendar feature into my app, I decided to create my own rather than use existing plugins due to not finding any that m ...

Ajax success handler failing to process JSON response despite receiving status code 200 or 304

My AJAX call is returning a JSON object successfully in the browser. However, instead of firing the success function, the error block is triggered with a message simply stating "error," which doesn't provide much information. The status returned is ei ...

Is there a way to apply -webkit-text-fill-color using pure vanilla JavaScript?

My website features two a links, and I am utilizing JavaScript to set their href attributes. When there is no link provided, the color changes to black. However, in Safari on iPhone, achieving the correct color requires the use of -webkit-text-fill-color ...

Is it possible to execute "green arrow" unit tests directly with Mocha in IntelliJ IDEA, even when Karma and Mocha are both installed?

My unit tests are set up using Karma and Mocha. The reason I use Karma is because some of the functionality being tested requires a web browser, even if it's just a fake headless one. However, most of my code can be run in either a browser or Node.js. ...

Having difficulty accessing the sound file despite inputting the correct path. Attempts to open it using ./ , ../ , and ../../ were unsuccessful

While attempting to create a blackjack game, I encountered an issue. When I click the hit button, a king card picture should appear along with a sound. However, the sound does not play and the error message Failed to load resource: net::ERR_FILE_NOT_FOUND ...

Mastering the art of sending HTML emails with Express.js

As a beginner in nodejs, I am displaying an html file on the home page (localhost). The file includes a contact form, and I would like to send an email to the user. Can you guide me on how to accomplish this task? Below is my current code. Thank you in a ...

Choose individual characters one by one

I am having issues with selecting the day, month, and year separately to calculate the days until due. It seems like my substr function may not be working correctly. Can you help troubleshoot why this is happening? http://jsfiddle.net/infatti/XeqPT/15/ f ...

The collada loader in three.js assigns the UV texture's color to every model in the scene

Apologies for my poor English skills. I am encountering an issue with the Collada loader in Three.js. In Blender, I have a cylinder with a UV texture applied to it, and when I render it everything looks fine. However, upon exporting and loading it into Thr ...

What is the best way to continuously click a JavaScript link until it disappears?

Many websites utilize single-page pagination to display more content with each click. It can be beneficial to view all the content on one page, such as for web crawling purposes. Much like automatically clicking a button using Greasemonkey, how can JavaScr ...

Issues with jQuery not detecting click events

Here is an example of HTML: <div class="sortable-buttons"> <ul> <li><a>Recent</a></li> <li><a>Popular</a></li> <li><a>Being Discussed</a></li> </ul> </div ...

Translating Encryption from Javascript to Ruby

I have an application which utilizes HTML5 caching to enable offline functionality. When the app is offline, information is stored using JavaScript in localStorage and then transmitted to the server once online connectivity is restored. I am interested in ...

The Google Books API has encountered an authentication error with status code 401

Trying to access public data using the Google Books API locally: An error occurred with the authentication credentials. It seems that an OAuth 2 access token, login cookie, or another valid authentication credential is missing. For more information, visit ...

creating links using json2html

I need assistance to create a clickable anchor using json2html with the following transformation: 'renderTimeline':[ { tag: "a", class: "btn btn-warning btn-circle", style: "float: right;", html: "<i class=\"icon-rem ...

loops with nested MongoDB queries

I am trying to optimize my MongoDB query by using a foreach loop that calls another mongodb query multiple times and pushes the results into an array with each request. The issue I'm facing is that this is an asynchronous call, so the line of code tha ...

Enhance Your Forms with Bootstrap 4 Validation Using JavaScript/jQuery

Exploring the world of web development, I have ventured into setting up a practice form to delve into the art of form validation. Utilizing Bootstrap's documentation for Custom Styles ensures compatibility with screen readers and presents a consistent ...

"Exploring One Direction: A bright spotlight on navigating with PointerLockControls in Threejs

My goal is to attach a directional flashlight to the camera (controls object) so that the beam always points towards the center of the screen. Here's the code I'm currently using: controls = new PointerLockControls( camera, document.body ); var f ...