RunJS icon indicating copy to clipboard operation
RunJS copied to clipboard

Binary Tree Issue

Open Aramantos opened this issue 4 years ago • 1 comments

I am just making a binary tree and it seems to get stuck like its an infinite loop regularly, I just need to save the file and reopen it and it runs fine but will eventually break again.

`class Node { constructor(value) { this.left = null; this.right = null; this.value = value; } }

class BinarySearchTree { constructor() { this.root = null; } insert(value) { const newNode = new Node(value); if (this.root === null) { this.root = newNode; } else { let currentNode = this.root; while(true) { if (value < currentNode.value) { //Left if (!currentNode.left) { currentNode.left = newNode; return this; } currentNode = currentNode.left; } else { //right if (!currentNode.right) { currentNode.right = newNode; return this; } currentNode = currentNode.right; } } } } lookup(value) { if(!this.root) { return false; } const searchNode = value; let currentNode = this.root; while (currentNode) { if (searchNode === currentNode) { console.log('found'); return currentNode; } if (searchNode > currentNode.value) { currentNode = currentNode.right; } else if (searchNode < currentNode.value) { currentNode = currentNode.left; } else if (currentNode.value === searchNode) { console.log('yes') return currentNode; } } return false; } }

const tree = new BinarySearchTree(); tree.insert(9); tree.insert(4); tree.insert(6); tree.insert(20); tree.insert(170); tree.insert(15); tree.insert(1);

tree.lookup(9);

JSON.stringify(traverse(tree.root))

// 9 // 4 20 //1 6 15 170

function traverse(node) { const tree = {value: node.value }; tree.left = node.left === null ? null : traverse(node.left); tree.right = node.right === null ? null : traverse(node.right); return tree; }`

Aramantos avatar Jun 26 '22 17:06 Aramantos

The issue will be due to the code containing an infinite loop:

while(true) {
if (value < currentNode.value) {
//Left
if (!currentNode.left) {
currentNode.left = newNode;
return this;
}

Infinite loops are best avoided as they will crash whichever environment they are running in. To resolve this in RunJS, you shouldn't need to restart the app, you can use the Kill action - found in the Action menu: Screenshot 2022-06-26 at 21 42 08

Hope that helps.

lukehaas avatar Jun 26 '22 20:06 lukehaas