I've experimented with binary tree examples and received the output in object form. Now, I'm wondering how I can extract the values from this object and convert them into

Issue Description A tree with N nodes rooted at 1 is given to you. Each node in the tree has a special number Se associated with it. Additionally, each node has a certain Power. The power of each node in the tree is defined as the count of heavy nodes in the subtree of that node (including the node itself). In this context, a heavy node is one for which the sum of divisors of its special number is a multiple of 3. You have been provided with Q queries.

There are two types of queries:

  • Type 1: Update special number of a node.
  • Type 2: Determine the power of a specific node.

Input Format

First line: Two space-separated integers N and Q denoting the number of nodes in the tree and the number of queries respectively. Each of the next N-1 lines: Two space-separated integers U and V indicating an edge between them. Next line: N space-separated integers where i-th integer denotes the special number related to node i. First integer in the next Q lines is T (the type of query). If T is 1, it is followed by 2 integers X and Y representing the update of special number S of node X to Y. If T is 2, it is followed by a single integer X.

Output Format

For each query of type 2, output the power of the given node X. Each answer for a query should be displayed on a new line.

Explanation of the Problem Statement Essentially, we are dealing with a tree structure with numbered nodes (Si) and possibly some children nodes due to the tree's nature.

The problem requires us to calculate the "Power" of a node, where power is determined by counting the number of "heavy nodes" within its children.

A "heavy node" is defined as a node whose sum of its divisors for Si is divisible by 3.

Various computations that need to be conducted include:

  • Identifying all child nodes for a given node.
  • Determining the divisors for each child node's number.
  • Summing up the divisors and checking if they are multiples of 3.

Given Sample Input and Outputs:

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

The code 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, I wish to convert this data into an array [16, 8, 17, 3, 18]

and find the divisors for each node, checking whether the divisors are divisible by 3 or not. How can I approach this?

Is my current approach correct?

Answer №1

My approach to solving the problem was as follows:

a) I precomputed the factor sums for each Special Number using the Sieve method, and if the sum was divisible by 3, I marked that node with a value of 1.
b) I then utilized a Depth First Search (DFS) traversal approach to calculate the sum of all nodes below including the current node. This operation has a time complexity of O(n).
c) While answering queries of Type 2 can be done in constant time, answering Type 1 queries proved to be more challenging. In the worst case scenario, my code was taking O(n) complexity due to updating the count of parent nodes for each node. With each query being on the order of 10^6 and n also being on the order of 10^6, the overall complexity becomes O(q*n), which is significantly higher than desired.

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

Peruse the written content and implement it within a div element

If any of the words match, I want to highlight them in a different color on the website for the user to see. var main = document.getElementById("selectedItem").innerText; var opinionTargets = ["screen", "cover", "size", "waterproof", "voice", "light", "pr ...

Creating a dynamic directive in AngularJS: Learn how to add or remove it from the DOM based on specific conditions

Suppose I have a customized modal directive that looks like this: return { restrict: 'E', templateUrl: 'modal.html', scope: { modalContent: "&", modalOpen: "&" } } And in the HTML: <ng-modal modal-content="co ...

What is the best way to incorporate an onmouseover event so that when the mouse hovers over an image, play/stop/pause buttons are displayed

Furthermore, each button should trigger an event on click. When the pause button is clicked, the button text should toggle between pause and continue, and the action should correspond to the displayed text. This is the HTML code I currently have: Includi ...

"Using the power of jQuery to efficiently bind events to elements through associative

I am attempting to link the same action to 3 checkboxes, with a different outcome for each: var checkboxes = { 'option1' : 'result1', 'option2' : 'result2', 'option3' : 'result3', }; ...

Ways to modify babel output file extensions

I'm facing an issue where babel --out-file-extension is not working as expected. Below is my package.json : { "name": "Assets", "version": "1.0.0", "description": "", "main" ...

Incorporating a Custom CKEditor5 Build into an Angular Application

I am currently in the process of developing an article editor, utilizing the Angular Integration for CKEditor5. By following the provided documentation, I have successfully implemented the ClassicEditor build with the ckeditor component. Below are the ess ...

Transitioning to Vue 3 has introduced a change where prop types are now classified

During the process of migrating the application from Vue 2 to Vue 3 by following this guide: , I encountered an issue related to Props and their types. All props were marked as type unknown by the linter, even though no errors were shown in the template it ...

Three.js: Obtain the latest vertex positions using morph targets

I have successfully implemented some morph targets in my project: View the working morph targets here (Don't forget to use the slider control to see the morph effect in action) However, I am facing an issue where I cannot access the updated position ...

Designing scroll boxes that are not continuous and tracking the time spent in each section

I'm seeking assistance with a unique challenge involving the creation of scroll boxes for use in a Qualtrics survey and tracking the time spent viewing different sections of text within them. Specifically, I aim to design a scroll box featuring two p ...

What is the best way to refresh the data in my list when a subitem is updated through a GET request using RTK Query?

Having a good understanding of the RTK query concept, I am facing a specific use case where I require some guidance. In my application, there is a list component and a details component that allows users to navigate and view more information about a parti ...

Node.js encountered an error: TypeError - req.end does not have a function

Encountering an error stating that req.end is not a function, even though it works elsewhere in the code. Upon researching, some sources suggest that the global req variable might have been misplaced or lost. However, I haven't used any other variabl ...

failure of pipe during search for art gallery information

Hi, I've created a filter pipe to search for imagenames and imageids among all my images. However, it seems to only find matches in the first image. There seems to be something wrong with my code. This is my FilterPipe class in filter.pipe.ts where I ...

Reading Properties in VueJS with Firebase

<template> <div id="app"> <h1 id="title"gt;{{ quiz.title }}</h1> <div id="ques" v-for="(question, index) in quiz.questions" :key="question.text"> <div v-show="index = ...

A sticky sidebar in HTML that is confined to a specific div element

I'm working on creating an HTML sidebar that is constrained to the size of a div (not full-screen like typical sidebars) and also sticky. This means that when the height of the div exceeds the screen's height, the sidebar should stick to the scre ...

jQuery's height calculations for elements are inaccurate

I have a total of seven divs, each with the class "row". Initially, their content is hidden but there is a timeline that spans from the first row to the last one. The height of the timeline is calculated dynamically based on the combined heights of all row ...

Angular's alternative to jQuery deferred.always() callback

Utilizing the .always() callback function in jQuery allows us to manage responses, regardless of whether they are successful or not. Is there a similar functionality in AngularJS that serves the same purpose? //jQuery $.get( "test.php" ).always(function( ...

Refresh jQuery DataTable with updated search results

I have a function that loads the DataTable once the document is loaded. $(document).ready(function() { var $dataTable = $('#example1').DataTable({ "ajax": 'api/qnams_all.php', "dataType": "json", "bDestroy": true, "s ...

Top Recommendations: Comparing Standalone Components and Modules in Angular Version 14

I'm in need of some clarification on the most effective practices when it comes to utilizing standalone components and modules within Angular 14. With the introduction of standalone components as a new concept in Angular, I am seeking factual guidance ...

Encountering a TypeError when using the react useRef() hook

During my work on an app utilizing the webRTC API and working with the useRef() hook in React, I encountered an error Error: TypeError: myVideo.current is undefined ContextProvider SocketContext.js:27 promise callback*ContextProvider/< SocketCon ...

Sending multiple ajax requests with identical data

I have been trying to send multiple requests to the same URL. The goal is to ban all the users that are included in the 'users' array by sending individual POST requests for each user. However, I am facing an issue where I keep getting the same d ...