// 函数版
let strArr = 'ABEF##G##D##C##'.split('')
function Node(data = '#') {
this.data = data
this.lChild = null
this.rChild = null
}
function createTreeNode(node) {
if (strArr.length) return
let str = strArr.shift()
if (str === '#') return
console.log(strArr)
node.data = str
if (strArr[0] !== '#') {
node.lChild = new Node()
}
createTreeNode(node.lChild)
if (strArr[0] !== '#') {
node.rChild = new Node()
}
createTreeNode(node.rChild)
}
let fnTree = new Node()
createTreeNode(fnTree)
console.log(fnTree)
// 先序遍历结果
function ProOrderTraverse (node) {
if (node === null) return
ProOrderTraverse(node.lChild)
ProOrderTraverse(node.rChild)
}
/*
空数组:空结点
数组:在根结点上构造左子树、右子树
*/
class BiTree {
root = null
arr = []
constructor (arr) {
this.arr = arr
// 初始化一个结点
this.root = new Node()
}
// 构建左子树、右子树、空结点
createNode (node) {
if (!this.arr.length) return
const str = this.arr.shift()
// 空结点不需要在构建左子树、右子树了
if (str === '#') return
node.data = str
// 开始建立左子树
if (this.arr[0] !== '#') {
node.lChild = new Node(str)
}
this.createNode(node.lChild)
// 构造右子树
if (this.arr[0] !== '#') {
node.rChild = new Node(str)
}
this.createNode(node.rChild)
}
}
// 树的字符串
let strArrObj = 'ABEF##G##D##C##'.split('')
let biTreeObj = new BiTree(strArrObj)
biTreeObj.createNode(biTreeObj.root)
console.log(biTreeObj.root)
console