Binary Search Tree
by tanya_22
HTML
<h1>Hi Binary Search Tree ☀️</h1>
<div class="playground">
<div class="todo">
<input type="checkbox" checked>class realisation<br>
<input type="checkbox" checked>insertNode<br>
<input type="checkbox" checked>removeNode<br>
<input type="checkbox" checked>findNode<br>
</div>
<pre id="bts"></pre>
</div>
CSS
body {
background: grey;
}
h1 {
color: #fcbe24;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.playground {
display: flex;
width: 100%;
flex-direction: column;
justify-content: space-around;
}
JavaScript
class BTS {
constructor(value) {
this.left = null;
this.right = null;
this.value = value;
}
insertNode(value) {
return this._insertNode(value, this);
}
_insertNode(value, parent) {
if (value < parent.value) {
if (parent.left === null) {
parent.left = new BTS(value, parent);
} else {
this._insertNode(value, parent.left);
}
} else {
if (parent.right === null) {
parent.right = new BTS(value, parent);
} else {
this._insertNode(value, parent.right);
}
}
}
create(root) {
root.insertNode(5);
root.insertNode(2);
root.insertNode(1);
root.insertNode(13);
root.insertNode(8);
root.insertNode(15);
root.insertNode(12);
}
}
function traverse(root) {
if (root != null) {
traverse(root.left);
console.log(" " + root.value);
traverse(root.right);
}
}
const bts = new BTS(10);
bts.create(bts);
console.log({bts});
const hasSumTarget = (root: BTS, target: number): boolean => {
if (root == null) {
return false;
}
if (!root.left && !root.right) {
return root.value === target;
}
return hasSumTarget(root.left, target - root.value) || hasSumTarget(root.right, target - root.value);
}
function minDepth(root: BTS): number {
debugger;
if (!root) {
return 0;
}
if (!root.left && !root.right) {
return 1;
}
let left = minDepth(root.left);
let right = minDepth(root.right);
return 1 + Math.min(left, right);
}
/* console.log(minDepth(bts)); */
console.log(minDepth(bts));