I obtained the binary tree output in the form of an object. How can I extract the values from this object and store them in an array to continue working on

Issue Statement In this scenario, you have been presented with a tree consisting of N nodes that are rooted at 1. Each node in the tree is associated with a special number, Se. Moreover, each node possesses a certain Power, which is determined by the count of heavy nodes in the subtree of the respective node (inclusive of the node itself). A heavy node is defined as a node whose total sum of divisors of its special number is a multiple of 3. There are Q queries provided.
The two types of queries available are: Type 1: Update the special number of a specific node. Type 2: Determine the power of a given node.

Input Structure

Initial Line: Two integers N and Q separated by space indicating the total number of nodes in the tree and the number of queries respectively. Subsequently, each of the following N-1 lines includes two space-separated integers U and V signifying an edge between them. Next line: N space-separated integers where i denotes the special number connected to node i. The first integer in the next Q lines stands for T (the query type). If T is 1, it is succeeded by two integers X and Y specifying that the special number S of node X needs to be updated to Y. In case T is 2, it will be followed by a single integer X.

Outcome Scheme

For every Type 2 query, disclose the power of the specified node X. Each query's response should be displayed on a new line.

Explanation of the Problem Statement Essentially, we are confronted with a tree comprising numbered nodes (Si), some of which are likely to have child nodes (as per the tree structure).

The issue seeks to ascertain the "Power" of a node, wherein power is interpreted as the count of "heavy nodes" among its children.

A "heavy node" is identified as a node whose sum of divisors for Si is a multiple of 3.

Several assessments need to be made here:
* For a given node, identification of all its child nodes is imperative
* Determination of the divisors for each child node's number is essential
* Aggregation of the divisors and validation of divisibility by 3

Provided Sample Input and Outputs Like

Sample Input

5 5

1 2

1 3

3 4

3 5

16 8 17 3 18

2 1

2 3

1 3 7

2 1

2 3

Sample Output

3

2

2

1

Code That I Attempted

function BinarySearchTree() {
  this.root = null;
}

BinarySearchTree.prototype.insertNode = function (val) {
  var node = {
    data : val, 
    left : null, 
    right : null
  };

  var currentNode;

  if (!this.root) {
    this.root = node;
  } else {
    currentNode = this.root;
    while (currentNode) {
      if (val < currentNode.data) {
          if (!currentNode.left) {
            currentNode.left = node;
            break;
          } else {
            currentNode = currentNode.left;
          }
      } else if (val > currentNode.data) {
        if (!currentNode.right) {
          currentNode.right = node;
          break;
        } else {
          currentNode = currentNode.right;
        }
      } else {
        break;
      }
    }    
  }
};

var BST = new BinarySearchTree();

BST.insertNode(16);
BST.insertNode(8);
BST.insertNode(17);
BST.insertNode(3);
BST.insertNode(18);

console.log(BST);

My Output

BinarySearchTree {
  root:
   { data: 16,
     left: { data: 8, left: [Object], right: null },
     right: { data: 17, left: null, right: [Object] } } }

Now, my objective is to convert this data into an array like [16, 8, 17, 3, 18]

and then proceed to calculate the divisors of each node and determine whether these divisors are divisible by 3 or not. What would be the appropriate approach for accomplishing this?

Is the method employed correct?

Answer №1

Give this a try:

function printLevelOrderTree (myBST) {
  var temporary, myQueue = [];

  myQueue.push(myBST.root);

  while (myQueue.length) {
    // Dequeue the Queue
    temporary = myQueue.splice(0, 1)[0];

    console.log(temporary.data);

    // Enqueue the Queue
    if (temporary.left) myQueue.push(temporary.left);
    if (temporary.right) myQueue.push(temporary.right);
  }
}

printLevelOrderTree(myBST);

The result will be displayed as an array.

Answer №2

If you find that displaying as an array is insufficient (edited by GAUTAM KUMAR):

 function createArrayFromBST(BST) {
  let result = [];
  let queue = [];

  queue.push(BST.root);

  while (queue.length > 0) {
    let tempNode = queue.splice(0, 1)[0];
    result.push(tempNode.data);
    if (tempNode.right) queue.push(tempNode.right);
    if (tempNode.left) queue.push(tempNode.left);
  }
  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

Field for user input along with a pair of interactive buttons

I created a form with one input field and two buttons - one for checking in and the other for checking out using a code. However, when I submit the form, it leads to a blank page in the php file. What could be causing this issue? UPDATE After changing fro ...

Creating a Selectable Child Form in ReactJS that Sends Data to Parent Form

Sorry for the lack of details, I'm struggling to explain this situation clearly. I'm currently learning ReactJS and JS. In a project I am working on, I have the following requirements: There is a form where users can input text and numbers. The ...

Utilize the identical function value within a Vue template

In my template, I am encountering a recurring situation where I need to retrieve a value from a function. This function takes parameters from the template (such as the index of a v-for loop) and returns a result that is then displayed on the template. The ...

Unable to retrieve the most recent global variable value within the confirmation box

<script type="text/javascript"> var customDiv ="hello"; $(function () { var $form = $("#authNotificationForm"); var startItems = $form.serializeArray(); startItems = convertSerializedArrayToHash(startItems); $("#authNoti ...

Utilizing a setTimeout function within a nested function in JavaScript

Recently delving into the world of JavaScript, I encountered an issue with a code snippet that goes like this: function job1() { var subText1 = ""; var subText2 = ""; var text = ""; var vocabulary = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijkl ...

Transform seconds into an ISO 8601 duration using JavaScript

Dealing with ISO 8601 durations can be quite tricky. Efficiently converting seconds to durations is my current challenge, especially in JavaScript. Stay tuned for my solution and the Jest test script coming up next. ...

Angular 9 Issue: Failure to Display Nested Mat-Tree Children

Hello everyone, I'm new to posting questions on Stack Overflow and I'm seeking some assistance with an issue I'm having with Mat-Tree. Despite the fact that my data is present when I console log it, the children are not appearing. I am fetc ...

Why won't my Laravel AJAX request work after refreshing the page?

In my Laravel CRUD web application, users can view and edit records with a sorting feature that asynchronously sorts the main records view using AJAX. Everything functions smoothly until a user clicks on a record to edit it. After being redirected through ...

Looping through elements using .each in jQuery and accessing their values in the following iteration

Here is the code snippet I've been working on: var index=0; var load=0; $("td.load_ads").each(function(){ var loading=$(this); $.post('/self_coded_helpers/jpost_get_ads.php',{index:index,type:'fetch_id' ...

What are the appropriate situations for utilizing getStaticPaths()?

Right now, an API call is being made in a main component and the fetched data is saved in a Singleton. This singleton data needs to be accessed by the getStaticPaths() function. However, due to the fact that getStaticPaths() pre-renders it, the singleton ...

JavaScript Money Exchange

Can currency be recalculated using JavaScript or jQuery? For instance: <div id="price">$99.00</div> Could become <div class="gbp" id="price">£63.85</div> If a class of "GBP" was added to the div tag? ...

Tips on incorporating jQuery cross-domain functionality

Attempting to retrieve and display the firstName data from this URL: http://www.w3schools.com/jquery/demo_ajax_json.js, as part of a test for another project. Encountered the error message: Origin null is not allowed by Access-Control-Allow-Origin, prompt ...

Unable to store user data in the MongoDB Database

I'm currently facing an issue while trying to store user information in my MongoDB database. Everything was working fine until I implemented hashing on the passwords using bcrypt. After implementing password hashing, I am encountering difficulties in ...

Is it possible to adjust the CSS code linked to the HTML tag based on the specific webpage being viewed?

I am facing an issue with the homepage of my website, which uses Scrollmagic.js for smooth scrolling. In order for the sticky footer CSS to work properly on all other pages, the HTML tag needs to have a height of 100%. However, if I add this height value t ...

Changing an object into an array for saving and transforming it back to an array for usage in JavaScript

I am dealing with a unique situation where I have an object created from dynamic checkboxes in Angular. The structure of the object looks like this: {"United States":true,"Canada":true,"Australia":false} While this format works well for storing values, I ...

Error message encountered when deploying a Discord bot on Heroku: "SyntaxError: Unexpected token '??='"

I encountered an issue when trying to deploy a Discord bot that I created using Node.js on Heroku. The error message is as follows: 2021-11-05T00:00:10.334347+00:00 app[web.1]: > node . 2021-11-05T00:00:10.334348+00:00 app[web.1]: 2021-11-05T00:00:10.3 ...

How to exclude specific {} from TypeScript union without affecting other types

Consider the following union type: type T = {} | ({ some: number } & { any: string }) If you want to narrow this type to the latter, simply excluding the empty object won't work: type WithEntries = Exclude<T, {}> This will result in neve ...

There is a complete absence of text appearing on the html page when Angular is

Currently, I am in the process of learning Angular during my internship. As part of the requirements, I have been tasked with developing a client-server application using Angular as the frontend framework and Spring as the backend solution. Within the proj ...

How can I incorporate multiple JSX files into plain HTML without using npm?

I have a question regarding importing JSX files in an HTML file without using npm and directly running it with LiveServer. I have two files, index.js and app.jsx, that I want to connect within my index.html script. How can I achieve this? Code: index.html ...

Tips for obtaining the most recent HTML element in Angular

I was able to include HTML content in an Angular (7) UI using the DomSanitizer this.sanitizer.bypassSecurityTrustHtml("htmlstr") Once the content is sanitized and displayed in the HTML view, users have the ability to modify the values as desired ...