BST
villainHR
by THR jimmy
Babel + JSX
'use strict';
class Node {
constructor(value, left, right) {
this.value = value;
this.left_child = left;
this.right_child = right
}
}
class BST {
constructor(root) {
this.root = root;
}
child_contain(node, value) {
if (node.left_child !== null) {
if (node.left_child.value === value) {
return [true, 'left_child'];
}
}
if (node.right_child !== null) {
if (node.right_child.value === value) {
return [true, 'right_child']
}
}
return [false, 'null']
}
findParent(value, node = this.root) {
let has, child;
while (true) {
if (node === null) {
// 如果节点为空,返回null
return null;
}
[has, child] = this.child_contain(node, value)
if (has) {
// 找到父节点
return [node, child]
} else {
// 没有则继续遍历
if (node.value > value) {
// 查找左子节点
node = node.left_child;
} else {
// 查找右子节点
node = node.right_child;
}
}
}
}
find(value, node = this.root) {
while (true) {
if (node === null) {
// 如果节点为空,返回null
return null;
} else if (node.value === value) {
// 找到对应的值并返回
return node;
} else if (node.value > value) {
// 查找左子节点
node = node.left_child;
} else {
// 查找右子节点
node = node.right_child;
}
}
}
max(node = this.root) {
while (true) {
if (node.right_child !== null) {
node = node.right_child;
} else {
return node;
}
}
}
...