最近研究了一下二叉树,闲来没事用js自己动手实现了一遍,欢迎各位大牛拍砖
一个二叉树数据结构的属性一般包含:节点及节点的值(代码中的node);节点之间的边关系(连接关系,代码中的line)
// 二叉树对象实现
function binaryTree (opt) {
let tree = {
node: opt.node,
line: opt.line,
isVisited: [],
findFather: function (x) {
for (let i = 0; i < this.node.length; i++) {
if (this.line[i][x] === 1) {
console.log('找到父对象为' + i)
return i
}
}
},
findFirstChild: function (x) {
for (let i = 0; i < this.node.length; i++) {
if (this.line[x][i]) {
// console.log('找到第一个子对象' + i)
return i
}
}
return -1
},
findSecondChild: function (x) {
let y = -1
for (let i = 0; i < this.node.length; i++) {
if (this.line[x][i]) {
if (y === -1) {
y = i
} else {
// console.log('找到第二个子对象' + i)
return i
}
}
}
return -1
},
findLeaf: function () {
let result = []
for (let i = 0; i < this.node.length; i++) {
if (this.findFirstChild(i) === -1) {
result.push(i)
}
}
return result
},
// 深度循环
deepLoop: function (isVisited, root, result) {
isVisited[root] = true
console.log(root + '深度遍历')
result.push(root)
root = this.findFirstChild(root)
while (root !== -1) {
if (!isVisited[root]) {
this.deepLoop(isVisited, root, result)
}
root = this.findSecondChild(root)
}
},
// 深度优先遍历
deepTraversing: function (isVisited) {
let result = []
for (let i = 0; i < this.node.length; i++) {
if (!isVisited[i]) {
this.deepLoop(isVisited, i, result)
}
}
console.log(result)
}
}
return tree
}
题目:从二叉树的根到叶子节点称为一条路径,路径上的每个节点的value之和为路径和值,是否存在一条和值为N的。
// 找到一个等于N的链路
function find (N) {
let opt = { node: [1, 4, 2, 2, 5, 2, 7],
line: [
[0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]] }
let tree = this.binaryTree(opt)
let isVisited = [false, false, false, false, false, false, false]
tree.deepTraversing(isVisited)
let leaf = tree.findLeaf()
let result = []
for (let i = 0; i < leaf.length; i++) {
let x = leaf[i]
let value = tree.node[x]
let res = []
res.push(x)
while (x) {
x = tree.findFather(x)
value += tree.node[x]
res.push(x)
}
if (value === N) {
result = res
}
}
console.log(result)
return result
}