Discovering the items nestled within the branches of a tree structure, starting from the root and traversing down

My tree data structure has a unique layout:

[
  {
    info: object,
    children:
      [ ...other objects... ]
  },
  ...other objects...
]

The structure can vary in its shape and number of nodes.

I have developed a method that recursively identifies and retrieves the path (an array of intermediate objects) between the root r and a specific object o. (it does not matter whether r and o are included)

public getPath(tree: Array<object>, o: object): Array<object> {

  let path: Array<object> = [];

  function explore(subtree: Array<object>): void {
    for (let node of subtree) {

      path.push(node['info']);
      if (node['info'] == o) return;
      else if (node['children'].length > 0) explore(node['children']);
      else path = [];

    }
  }

  explore(tree);
  return path;

}

Essentially, my strategy involves:

  • Adding every visited object to the array during traversal from r to o,
  • Resetting the array if a different path than r to o is encountered,
  • Ending the process when reaching o where traversal concludes.

Results:

  • This method successfully returns [r] when r is specified as o.
  • It also provides the correct path [r, first child of r] when the first child of r is selected as o.
  • However, choosing any other object as o results in returning objects beyond the desired path along with those on the correct route.

Answer №1

Your code has a flaw due to the use of a global array called path, which is outside the scope of function f. You are clearing the entire array if a node doesn't match, when you should only be cutting out the current part. There are two approaches to solving this issue: one is to modify function f so that it accepts an array path as a parameter which it copies and passes recursively until it finds the object. The other, more optimal way, is to leverage the call stack created by recursion.

public getPath(tree: Array<object>, o: object): Array<object> {

    function f(subtree: Array<object>) {
        for (let node of subtree) {
            if (node.data == o) {
                return [node];
            } else if(node.subs.length) {                             
                let result = f(node.subs);                            
                if(result) {                                          
                    result.unshift(node);                             
                    return result;                                   
                }
            }
        }
        return null;
    }

    return f(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

Adapt the dimensions of the iframe to perfectly match the content within

Looking for a way to dynamically adjust the size of an iframe to perfectly fit its content, even after the initial load. It seems like I'll need some kind of event handling to automatically adjust the dimensions based on changes in the content within ...

Issues with Jquery keyup on Android devices - unable to detect keyup

I have not tested this code on an iPhone, but I am certain (tested) that it does not work on Android mobile devices: $('#search').live('keyup',function(key){ if(key.which == 13){ /*ANIMATE SEARCH*/ _k ...

Using Backbone to Retrieve a JSON File from a Server: Deciding Whether to Include the File Extension ".json" in the URL or URLRoot

Exploring Backbone with exercise by trying to obtain a JSON file from the server using the urlRoot property of the Model. Encountered an error (404) when setting urlRoot: "./js/json/todo", paths with ".json" work but console.log(todoItem.get('descrip ...

Strategies for capturing and incorporating Meteor.Error notifications from Meteor.Methods into a client-side database?

I am currently working on creating an error notification panel in Meteor. I have set up a client-side MongoDB, but I am encountering an issue with pushing Meteor.Error messages into that client-side database using the throwError function. Currently, the er ...

Load HTML table values dynamically with Ajax post page load in PHP

My goal is to retrieve the connectivity status of available servers in a database on a PHP page. <tbody> <?php foreach ($data['servers'] as $server) { ?> <tr> <td class=""><?php echo $server->server_ ...

AngularJS - Exchange data between controllers through shared scope

I've encountered a situation with a textarea in my HTML that looks like this: <textarea ng-model="commentBox"></textarea> In one of my controllers, I can easily access the content of the textarea using "$scope.commentBox". However, I&apo ...

How to retrieve the content of an iframe's head using jQuery

Is there a way to extract the content of the head section from an iframe? <iframe> <html> <head> <style>body{color:red;}</style> <link type="text/css" rel="stylesheet" href="some link"> </head& ...

Avoiding duplicate clicks in Onsen UI Navigator.Avoid duplicate clicks in

When a user clicks on an item in my list, they are taken to a details page. However, if the user clicks too quickly, two click events may be fired, leading them to navigate to two different pages consecutively. Is there a way to prevent this issue? Can we ...

Unlocking hidden gridview column values with the power of jQuery

Within my gridview control, there are 4 columns, with one column being invisible which contains the Email Address information. <asp:GridView id='gridData' runat='server'> <Columns> <asp:TemplateField> ...

Executing the last item in a for loop multiple times can lead to unexpected outcomes in JavaScript

I am currently in the process of developing a JavaScript/jQuery version of a dice game that my friends and I enjoy playing. The latest iteration is designed for 3 players: http://codepen.io/jwnardini/pen/jmygqd My goal is to allow users to select the num ...

Fatal error: The main module could not be located. Please check the path `/src/test.ts` for resolution errors

I am encountering an issue while trying to execute the unit test for my Angular 2 Application using ng test. The error message I keep receiving is: ERROR in Entry module not found: Error: Can't resolve '/Users/username/Dev/dashboard/src/test.t ...

Utilizing the dialogue feature within Angular 6

Situation: I am managing two sets of data in JSON format named customers and workers: customers: [ { "cusId": "01", "customerName": "Customer One", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

Implement feature to enable selection using jQuery

I have a question about implementing an <option value="fiat">Fiat</option>"> element into a dropdown list using jQuery. I've tried the code below and encountered some issues. When I click the button, I want to add the <option value= ...

When trying to access a certain class property, I was met with the following error message: TypeError: Unable to read/set property 'x' of

Lately, I've delved into the realm of JavaScript / TypeScript and decided to create a basic React App using TypeScript. Within one of my components, I aim to switch between different components using a "state" (where each component will follow the pre ...

Changing a Django QueryDict into an array of objects

When passing an array of objects within an ajax call, the code might look like this: function sendAjax(ajax_data) { return $.ajax({ url: '/ajax/ajaxprocess/', data: ajax_data, dataType: 'json', success: function (data) ...

Angular 7 - Creating tooltips with multiline text

I've utilized template strings to create a multi-line string. toolTip = ` ${Test} : ${number} ${Test} : ${number} ${Test} : ${number} ${Test} : ${number} ${Test} : ${number}}`; The issue I'm facing is that w ...

Attempting to showcase the data stored within MongoDB documents on my website's user interface

I am facing difficulties in showing the data stored in my database on the front end of my grocery list app, which is built using the MERN stack. I have a form that successfully sends data to MongoDB and saves it upon submission. In order to retrieve the d ...

What is the role of the "prepare" function in AWS CDK constructs?

TL;DR: What is the role and purpose of the prepare(): void method in AWS CDK's Construct class? When and how should it be utilized or avoided? The information provided about prepare() states: prepare() function is called after child constructs have ...

Setting a background image in vanilla-extract/css is a straightforward process that can instantly enhance

I am brand new to using vanilla-extract/CSS and I have a rather straightforward question. I am attempting to apply a background image to the body of my HTML using vanilla-extract, but I am encountering issues as I keep getting a "failed to compile" error. ...

Exclude the footer from the index.html file by configuring it in the docusaurus.config.js file

From what I understand, the docusuarus.config.js file is responsible for translating specified information into HTML to construct your website. This translated information is then directed to the 'index.html' file. However, I am encountering an ...