构造并判断二叉搜索树-js
2021-04-24 02:28
标签:inf wal port 构造 || each rip str data 构造并判断二叉搜索树-js 标签:inf wal port 构造 || each rip str data 原文地址:https://www.cnblogs.com/ygjzs/p/12236479.htmlclass Node {
constructor (val) {
this.val = val
this.left = this.right = undefined
}
}
class Tree {
constructor (data) {
let root = new Node(data.shift())
// 遍历所有的数据
data.forEach(item => {
this.insert(root, item)
})
return root
}
insert (node, data) {
if (node.val > data) {
if (node.left === undefined) {
node.left = new Node(data)
} else {
this.insert(node.left, data)
}
} else {
if (node.right === undefined) {
node.right = new Node(data)
} else {
this.insert(node.right, data)
}
}
}
static walk (root) {
if (!root.left && !root.right) {
return true
} else if ((root.left && root.val root.right.val)) {
return false
} else {
return Tree.walk(root.left) && Tree.walk(root.right)
}
}
}
export default Tree
export {
Node
}