// 二叉樹實現思路
function
BinaryTree() {
var
Node =
function (
key) {
this.
key =
key;
this.
left =
null;
this.
right =
null;
};
var
root =
null;
var
insertNode =
function (
root,
newNode) {
if (
newNode.
key <
node.
key) {
if (
node.
left ===
null) {
node.
left =
newNode
}
else {
insertNode(
node.
left,
newNode)
}
}
else {
if (
node.
right ===
null) {
node.
right =
newNode
}
else {
insertNode(
node.
right,
newNode)
}
}
}
this.
insert =
function (
key) {
var
newNode =
new
Node(
key)
if (
root ==
null) {
root =
newNode
}
else {
insertNode(
root,
newNode)
}
}
// 查找有沒有最大的值
this.
max =
function () {
return
maxNode(
root);
}
var
maxNode =
function () {
if (
node) {
while (
node &&
node.
right !==
null) {
node =
node.
right;
}
return
node.
key
}
}
this.
search =
function (
key) {
return
searchNode(
root,
key)
}
var
searchNode =
function (
node,
key) {
if (
node ===
null) {
return
false
}
if (
key <
node.
key) {
return
searchNode(
node.
left,
key)
}
else
if (
key >
node.
key) {
return
searchNode(
node.
right,
key)
}
else {
return
true
}
}
}
var
nodes = [
8,
3,
10,
1,
6,
14,
4,
7,
13]
var
binaryTree =
new
BinaryTree();
nodes.
forEach(
function (
key) {
binaryTree.
insert(
key)
})