Skip to content
Advertisement

My check for whether a graph is a Binary Tree always returns false

I have this question that is medium level and couldn’t even think on how to solve this problem, my solution could be overkill as I have no idea on how to traverse a bunch of numbers in an array to check whether it is a binary tree or not. The program always returns false no matter what

If you have a better answer to the question that would be perfect

Have the function TreeConstructor(strArr) take the array of strings stored in strArr, which will contain pairs of integers in the following format (i1, i2) where i1 represents a child a node in a tree and the second integer i2 signifies that it is the parent of i1. For example if strArr is ["(1,2)", "(2,4)", "(7,2)"]

JavaScript

which you can see forms a proper binary tree. Your program should, in this case, return the string true because a valid binary tree can be formed. If a proper binary cannot be formed with the integer pairs, then return the string false. All of the integers within the tree will be unique, which means there can only be one node in the tree with the given integer value

Examples

JavaScript

I came out with an attempt, but it always returns false. Most likely my code is overkill.

JavaScript

This is the main function

JavaScript

Advertisement

Answer

You seem to have misunderstood the assignment. The function should return true when the represented tree is a binary tree, not necessarily a binary search tree.

Your code is creating a tree from the first element and then takes any next node to insert it into that tree keeping with the binary search property, without taking into account that the pair from the input demands that the first is a direct child of the second. (Your variable parentNode is not used for anything)

Instead, you should just look at the child-parent relationships that are given in the input as representing edges, and use that information to build the graph. Finally you should verify that that graph represents a binary tree. Think about what are the distinctive characteristics of a binary tree and how to verify them.

Hint 1:

No node should have two parents

Hint 2:

No node should have 3 children

Hint 3:

All upward paths should end in the same node (the root)

The spoiler solution below does not return true/false, but a string that indicates whether the tree is “ok”, or why it is not. This is more useful for debugging and still easy to convert to a boolean.

JavaScript

NB: I would name the function with an initial lowercase letter as it is the common practice to reserve initial capital letters for class names.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement