Skip to content

Commit

Permalink
traverse code
Browse files Browse the repository at this point in the history
  • Loading branch information
leafoflegend committed Mar 25, 2024
1 parent 1a82fbb commit a5f1225
Show file tree
Hide file tree
Showing 2 changed files with 137 additions and 7 deletions.
7 changes: 0 additions & 7 deletions reacto/find_max_value.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,5 @@ function locateMinValue() {
const values = [];

function accumulateTree(child) {
if (!child) {
return;
}

values.push(child.value);

accumulateTree(child.left);
accumulateTree(child.right);
}
137 changes: 137 additions & 0 deletions reacto/react_traverse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
class BinaryTree {
value = null;

left = null;

right = null;

constructor(value) {
this.value = value;
}

insert = (value) => {
if (value < this.value) {
if (!this.left) {
const createdNode = new BinaryTree(value);
this.left = createdNode;

return createdNode;
} else {
return this.left.insert(value);
}
} else {
if (!this.right) {
const createdNode = new BinaryTree(value);
this.right = createdNode;

return createdNode;
} else {
return this.right.insert(value);
}
}
}

retrieve = (value) => {
if (this.value === value) {
return this.value;
} else if (value < this.value) {
if (!this.left) {
return null;
} else {
return this.left.retrieve(value);
}
} else {
if (!this.right) {
return null;
} else {
return this.right.retrieve(value);
}
}
}

breadthSearch = () => {
const breadthArray = [];
const childrenToProcess = [];

breadthArray.push(this.value);

if (this.left) {
childrenToProcess.push(this.left);
}

if (this.right) {
childrenToProcess.push(this.right);
}

while (childrenToProcess.length) {
const nextChild = childrenToProcess.shift();

breadthArray.push(nextChild.value);

if (nextChild.left) {
childrenToProcess.push(nextChild.left);
}

if (nextChild.right) {
childrenToProcess.push(nextChild.right);
}
}

return breadthArray;
}

recursiveSearch = (type, searchFunc) => {
if (type === 'pre') {
searchFunc(this.value);
}

this.left?.recursiveSearch(type, searchFunc);

if (type === 'in') {
searchFunc(this.value);
}

this.right?.recursiveSearch(type, searchFunc);

if (type === 'post') {
searchFunc(this.value);
}
}
}

/*
5
3 7
2 4 8
*/

const root = new BinaryTree(5);
root.insert(3);
root.insert(7);
root.insert(2);
root.insert(4);
root.insert(8);

console.log('Breadth', root.breadthSearch());

// Pre-Order, Post-Order, In-Order

const preArray = [];
const postArray = [];
const inArray = [];

root.recursiveSearch('pre', (val) => {
preArray.push(val);
});

root.recursiveSearch('post', (val) => {
postArray.push(val);
});

root.recursiveSearch('in', (val) => {
inArray.push(val);
});

console.log('Pre', preArray);
console.log('Post', postArray);
console.log('In', inArray);

0 comments on commit a5f1225

Please sign in to comment.