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

Challenges in Power BI Custom Visual Development: Trouble setting height for div elements

Currently, I am working on creating a custom visual for Power BI that includes a leaflet map within a div element. However, the issue arises when I fail to set a specific height for the map, resulting in an empty visual. I have managed to set a fixed heigh ...

Integrating tooltips on Dimple.js line charts

A simplified network-style chart has been created using Dimple's line plot as the foundation. For example, please refer to this link: http://jsfiddle.net/cc1gpt2o/ myChart.addCategoryAxis("x", "Entity"); myChart.addCategoryAxis("y", "Entity").add ...

AngularJS is experiencing issues with the sorting filter 'orderBy'

I am experiencing an issue with sorting a table list that has three columns. I have implemented the ability to sort all columns in ascending and descending order. However, when I click on the -Tag to initiate the sorting process, I encounter the following ...

In the process of using SWRInfinite for React Infinite Scrolling, the initial call may be made

Can someone help me understand why my useGetItems hook, which imports the usePagination hook, keeps repeating the first call history every time I scroll? /items?_page=1&_limit=40 /items?_page=1&_limit=40 /items?_page=2&_limit=40 /items?_page=1 ...

Creating JPEG images with specified dimensions. How can you add W x H sizing to an image?

I have been searching for a Deno/TypeScript code snippet that can create basic images with dimensions embedded on them. I have provided an example of the code below, which generates images in JPEG format, base64, and dataURL. The code works by adding RGB ...

What is the most effective way to display a card with varying values depending on the user's input in a form?

For a while now, I've been grappling with a particular challenge. In my project, I am utilizing multiple states to display values within a card after they are entered into a form. The first state captures the values and modifies the initial state, whi ...

Determining the emptiness of an array in Postman using node.js

When I receive a response, it is in the following format: { "test1": [], "test2": [], "test3": [], "test4": null, "test5": [] } This is the response that I get after making a request. I need to verify whether test1 is empty or not. ...

Using Jquery and Ajax to add information to a database

One of the challenges I'm facing involves a page with three forms, each containing separate variables that need to be inserted into a MySQL database for viewing. My current script is working fine, even though I am aware that `mySql_` is deprecated but ...

Guidelines for setting up a universal Handler using React and AXIOS

In my current project, I am utilizing ReactJs and AXIOS. My goal is to implement a global error handler without having to add a catch statement to each request throughout the codebase. To achieve this, I have created a service that consolidates all request ...

DiscordJS is throwing a TS2339 error stating that the property 'forEach' is not found on the type 'Collection<string, GuildMember>'

Upon attempting to utilize the code provided, I encountered the error messages Property 'forEach' does not exist on type 'Collection<string, GuildMember> and Property 'size' does not exist on type 'Collection<string, ...

Running of code in <script> tag

At what point does the code inside script tags start executing? Does it happen in order? <html> <head> <title>Canvas tutorial</title> <script type="text/javascript"> function draw(){ var canvas = document.getElementById ...

Stop receiving notifications for channel events in Stream with the GetStream.io Chat API

I'm having trouble understanding how to stop listening for channel events in JavaScript using the Stream Chat API. According to the documentation: // remove the handler for all "message.new" events on the channel channel.off("message.new", myChanne ...

Implementing ESM in your next.config.js file is critical for optimizing

Currently, I am in the process of optimizing a Next.js project and came across the requirement to include type: 'module' in thepackage.json file. However, this led to an error being thrown: Error [ERR_REQUIRE_ESM]: Must use import to load ES Mo ...

What is the best way to prevent jest.mock from being hoisted and only use it in a single jest unit test?

My goal is to create a mock import that will be used only in one specific jest unit test, but I am encountering some challenges. Below is the mock that I want to be restricted to just one test: jest.mock("@components/components-chat-dialog", () ...

Incorporate additional form element functionalities using radio inputs

Recently, I created code that allows a user to duplicate form elements and add values by clicking on "add more". Everything is functioning properly except for the radio inputs. I am currently stuck on this issue. Does anyone have any suggestions on how I c ...

Using JavaScript to Access PHP Files

Would like to understand the process of calling a php file (test.php) from either "x:" or "y:" in the code below. var example1 = { x: ['giraffes', 'orangutans', 'monkeys'], y: [20, 14, 23], name: 'Most read', ...

Contrasting the two approaches to Insertion Sort

It appears to me that these two implementations are achieving the same goal. However, I would greatly appreciate it if you could also clarify whether they are performing equivalently in terms of efficiency (e.g. number of instructions executed). Thank yo ...

What is the technique for utilizing JavaScript to toggle the opening and closing of a Bootstrap 5 navbar dropdown?

My website is built using Bootstrap 5, and I am working on creating a navbar dropdown functionality. On desktop, I want the dropdown to open on hover and lead to a new page when clicked. However, on mobile, I only want the dropdown to open and close on cli ...

What are the different scenarios in AngularJS where $scope is utilized versus when var is utilized?

Which is more efficient in AngularJS: using var or $scope. for variables inside functions? I am asking this question because I recently came across information about $watch, $digest, and $apply in AngularJS. While I may not have fully grasped the concept ...

Angular $watch not working as expected

I have a specific directive code: .directive('myDirective', function(){ 'use strict'; return { restrict: 'A' , link: function(scope, element, attrs) { var count = 0; function d ...