Last active
September 3, 2025 00:19
-
-
Save AbeEstrada/d537541013ee378f0e702880f6c0b5fd to your computer and use it in GitHub Desktop.
Exercise: Binary Search Tree Insertion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(data) { | |
this.data = data; | |
this.left = null; | |
this.right = null; | |
} | |
} | |
function insert(root, data) { | |
if (root === null) { | |
return new Node(data); | |
} | |
if (data < root.data) { | |
root.left = insert(root.left, data); | |
} else if (data > root.data) { | |
root.right = insert(root.right, data); | |
} | |
return root; | |
} | |
function createBST(values) { | |
let root = null; | |
for (let value of values) { | |
root = insert(root, value); | |
} | |
return root; | |
} | |
function preOrder(root) { | |
const result = []; | |
function traverse(node) { | |
if (node === null) return; | |
result.push(node.data); | |
traverse(node.left); | |
traverse(node.right); | |
} | |
traverse(root); | |
return result; | |
} | |
function processData(input) { | |
const lines = input.trim().split("\n"); | |
const values = lines[1].split(" ").map(Number); | |
const root = createBST(values); | |
console.log(preOrder(root).join(" ")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment