Determine if an Array forms a Symmetric Tree using javascript

Looking to determine if an array of strings represents a Symmetric Tree or not.

The array will depict a binary tree, and the goal is to check if the tree is symmetric (a mirror image of itself). The structure of the array is similar to that of a binary heap, with null nodes represented by a "#" symbol.

For instance, if the input array strArr is

["1", "2", "2", "3", "#", "#", "3"]
, this corresponds to the following tree:

https://i.sstatic.net/1rfw6.png

Given the above input, the expected output should be the string true, indicating that the binary tree is symmetric.

Examples

Input: ["4", "3", "4"]
Output: false

Input: ["10", "2", "2", "#", "1", "1", "#"]
Output: true

Answer №1

Assuming the provided input represents a valid tree structure, where the length of strArr is one less than a power of 2.

function checkSymmetry(strArr) {
  for (let level = 0; (2 ** (level + 1)) - 1 <= strArr.length; level++) {
    let row = strArr.slice((2 ** level) - 1, (2 ** (level + 1) - 1));
    if (JSON.stringify(row) !== JSON.stringify(row.reverse())) {
      return false;
    }
  }
  return true;
}

let testArray = ["10", "2", "2", "#", "1", "1", "#"];
console.log(checkSymmetry(testArray))

Answer №2

algorithm used

 araay = ["10" , "2", "2", "#", "1", "1", "#"]
lets break this down into individual steps

step 1 = ["10"]
step 2 = [ "2", "2" ]
step 3 = ["#", "1", "1", "#"]

check for symmetry in each step except the first one

let's analyze step 3 .

step 3 = ["#", "1", "1", "#"]
split this into two arrays from the middle

step 3 1 = ["#", "1" ]
step 3 2 = ["1", "#"]

Now reverse step 3 2

step 3 2 = ["1", "#"]

now check if step 3 2 is equal to step 3 1

Repeat the above process for each step

If all steps mirror each other, the binary tree is considered a mirror image

const Input = ["10" , "2", "2", "#", "1", "1", "#"];
function isEqual(a,b)
{
  // if length is not equal
  if(a.length!=b.length)
   return false;
  else
  {
  // comapring each element of array
   for(var i=0;i<a.length;i++)
   if(a[i] !== b[i]){
    return false;
   }
    return true;
  }
}

// Response 
let symetric = true ;
let stepSymetric = true ;
let mirror = true ;
// length of input 
const length = Input.length ;
// const length = 31 ;

// lets create binary tree from it

const totalSteps =
      Math.log(length + 1)/Math.log(2) ;

// check for symetric binary tree
function checkInt(n) { return parseInt(n) === n };
 symetric = checkInt(totalSteps);

//now check for mirror
let goneArrayLength = 0 ;
for (let i = 0; i < totalSteps; i++) { 
  const cStep = Math.pow(2,i);
  
  const stepArray = [];
  // console.log(goneArrayLength);
  
  // now update the step array 
  const start = goneArrayLength ;
  const end =  goneArrayLength + cStep ;
  
  for (let j = start; j < end; j++) {
    stepArray.push(Input[j])
  }
  
  console.log(stepArray);
  // Now we have each step lets find they are mirror image or not
  // check for even length
  if(stepArray.length%2 !== 0 && i !== 0){
    stepSymetric = false ;
  }
  const partitation = stepArray.length / 2 ;
  const leftArray = stepArray.slice(0,partitation);
  const rightArray = stepArray.slice(partitation , partitation * 2);
  // console.log("leftArray");
  // console.log(leftArray);
  // console.log("rightArray");
  // console.log(rightArray);
  function mirrorCheck (){
    let check = false;
    if(cStep === 1){
      return true ;
    }
    let array1 = leftArray;
    let array2 = rightArray.reverse();
    // console.log("first");
    // console.log(array1);
    // console.log("second");
    // console.log(array2);
   let equal = isEqual(array1 , array2)
   // console.log(equal);
    check = true ;
    if(!equal){
      // console.log("Noooooooooooooooo")
      check = false ;
    }
    
    return check;
  }
  let mirrorC = mirrorCheck();
  
  if(!mirrorC){
    mirror = false;
  }
  goneArrayLength = goneArrayLength + cStep ;
}
console.log(mirror + " " + symetric + " " + stepSymetric )

if(mirror && symetric && stepSymetric ){
  console.log("Mirror Image");
  
}
else{
  console.log("Not mirror image")
}
// console.log(isSymetric);
// console.log(totalSteps);

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

Working with jQuery conditionals to manipulate JSON data

I'm working with JSON data that includes a field like this: "first_date": "2015-06-02" Using jQuery, I want to achieve something like this: if( valueOfFirstDate.substring(5, 6) == "06" ){ //change 06 to "June" } Can anyone guide me on how to e ...

Creating a multi-page form in AngularJS with Tab navigation

Hello, I am currently working on implementing a multi-stage form using AngularJS Tabs. Instead of using routes in this application, I am trying to achieve the desired functionality solely through tabs. app.controller('createProjectController', [ ...

Locate the two absent numbers in a set of whole numbers containing two omissions

Can you explain the process for this task? The values are disordered but fall within the range of [1..n]. For example, consider the array [3,1,2,5,7,8]. The correct answer is 4, 6. I came across a similar solution in another post, however I am struggling ...

How can I retrieve the name of an HTTP status code using JavaScript and AngularJS?

My web application is built using AngularJS, JS, JQ, HTML5, and CSS3. It interacts with our projects' REST API by sending various HTTP methods and manipulating the data received. The functionality is similar to what can be achieved with DHC by Restlet ...

How can Angular incorporate JSON array values into the current scope?

I am currently working on pushing JSON data into the scope to add to a list without reloading the page. I am using the Ionic framework and infinite scroll feature. Can someone please point out what I am doing wrong and help me figure out how to append new ...

Encountering a problem with the persistent JavaScript script

I have implemented a plugin/code from on my website: Upon visiting my website and scrolling down, you will notice that the right hand sidebar also scrolls seamlessly. However, when at the top of the screen, clicking on any links becomes impossible unless ...

Using NodeJS to incorporate an array of strings into a PostgreSQL query

I'm currently working on a PostgreSQL query in Node.js using a pool created with the node-postgres package. The goal is to insert a new row into a table where one of the columns is of type text[]. Here's my code snippet: pool.query('INSERT I ...

The variable in Angular stopped working after the addition of a dependent component

Currently, I am working with Angular and have implemented two components. The first component is a navigation bar that includes a search bar. To enable the search functionality in my second component (home), I have added the following code: HTML for the n ...

Having trouble with JQuery Tooltip content not being overridden as expected

Hey, I'm having an issue with the tooltip in my code snippet on JSFiddle. The text specified in JQuery's tooltip content option is not replacing the tooltip as expected. Can someone help me figure out what I might be doing wrong or missing? Than ...

Who is the top earner among the employees in the array?

I have successfully calculated the "least" earned, but I am having issues with the code for determining the worker who earned the "most"... this is what I currently have. for (int i = 0; i < workerGrossIncome.Length; i++) ...

Eliminating elements from the center of an array

As part of a programming project, I've been tasked with creating array methods to perform various operations. This time, I needed to develop a function that removes the middle element if the array's length is odd, or both middle elements if the l ...

Using Vue to dynamically upload multiple files simultaneously

Although this question has been asked frequently, most of the answers do not address a key issue - how to upload multiple images while knowing which image belongs to which data. Attempting to bind v-model to input file doesn't work as expected, and ev ...

Is there a way to determine the path of the fetch function within a PHP file?

I am using a JavaScript function to retrieve data from the backend server async getAllExpensesByUser() { let response = await fetch("router.php/getAll"); return response.json(); } My question is, how can I retrieve the path "/getAll ...

Unveiling the Masked Phone Number in jquery.maskedinput for Database Insertion

Currently, I am grappling with removing the phone number mask while working with jquery.maskedinput.min.js in an MVC web app. Here is the JavaScript code snippet I am using: @section Scripts { @Scripts.Render("~/bundles/jqueryval") <script type="text/ ...

Can process.env.NODE_ENV be found within Azure App Service?

I am integrating NodeJS with my Angular application using ExpressJS. I came across an npm package called norobot that I want to install in order to utilize the process object. I need guidance on how and where to set the NODE_ENV in an App Service on Micro ...

Integrating an external JavaScript library into the codebase

I created a web radio player using Vue Cli and now I need to incorporate a new feature with an external library, specifically designed for handling audio advertisements. The catch is that this library must be loaded from a remote server and cannot be simpl ...

Validating a single field for City, State, and ZIP in jQuery/JavaScript

I am trying to validate an input field that requires City, State (two letter abbreviation), and ZIP code (5 numeric digits) in the format 'City, State ZIP'. Could someone please help me with validating this specific format and characters? Appre ...

Incorporate a progress bar into the Material-UI table design

I have the following example of a Material-UI table: import React from "react"; import clsx from "clsx"; import { createStyles, lighten, makeStyles, Theme } from "@material-ui/core/styles"; import Table from "@mat ...

Three.js - The variable "i" in question is not defined and has caused an Uncaught

I'm currently immersed in a project using three.js with the assistance of the parcel bundler. Everything seems to be functioning perfectly on my local setup. However, upon attempting to deploy it on Netlify, I encounter the following error: Uncaught ...

What could be causing my UI Bootstrap datepicker-popup to suddenly stop functioning?

After updating to UI Bootstrap 0.11.0, I encountered an issue where my datepickers were no longer appearing correctly. To demonstrate this problem, I have created a plunker which can be viewed here. Essentially, the code snippet causing the problem is as f ...