Skip to content

Commit

Permalink
feat: finish BST print
Browse files Browse the repository at this point in the history
  • Loading branch information
andy922200 committed Apr 5, 2024
1 parent 847c921 commit 90df010
Showing 1 changed file with 64 additions and 9 deletions.
73 changes: 64 additions & 9 deletions app-ch9-13.js
Expand Up @@ -9,6 +9,8 @@ class Node {
class BinarySearchTree {
constructor() {
this.root = null;
this.path = '';
this.queue = [];
}

treeInsert(z) {
Expand All @@ -28,15 +30,68 @@ class BinarySearchTree {
y.right = z;
}
}

preOrder(n){
if(n !== null){
this.path += n.key + ' ';
this.preOrder(n.left);
this.preOrder(n.right);
}
}

inOrder(n){
if(n !== null){
this.inOrder(n.left);
this.path += n.key + ' ';
this.inOrder(n.right);
}
}

postOrder(n){
if(n !== null){
this.postOrder(n.left);
this.postOrder(n.right);
this.path += n.key + ' ';
}
}

bftt(n){
if(n !== null){
this.queue.push(n);
for(let i=0; i<this.queue.length; i++){
const currentNode = this.queue[i];

if(currentNode){
if(currentNode.left){
this.queue.push(currentNode.left);
}
if(currentNode.right){
this.queue.push(currentNode.right);
}
}
}
}
}
}

const bst = new BinarySearchTree();
bst.treeInsert(new Node(15));
bst.treeInsert(new Node(6));
bst.treeInsert(new Node(5));
bst.treeInsert(new Node(1));
bst.treeInsert(new Node(13));
bst.treeInsert(new Node(-7));
bst.treeInsert(new Node(3));
const bst1 = new BinarySearchTree();
const bst2 = new BinarySearchTree();
const bst3 = new BinarySearchTree();
const bst4 = new BinarySearchTree();
const seeds = [15, 6, 5, 1, 13, -7, 3];

seeds.forEach(seed =>{
bst1.treeInsert(new Node(seed));
bst2.treeInsert(new Node(seed));
bst3.treeInsert(new Node(seed));
bst4.treeInsert(new Node(seed));
})

console.log(bst);
bst1.preOrder(bst1.root)
bst2.inOrder(bst2.root)
bst3.postOrder(bst3.root)
bst4.bftt(bst4.root)
console.log('PreOrder:', bst1.path)
console.log('InOrder:', bst2.path)
console.log('PostOrder:', bst3.path)
console.log('BFTT:', bst4.queue.map(node => node.key).join(' '))

0 comments on commit 90df010

Please sign in to comment.