将数组[‘A’,‘B’,‘C’,‘D’,‘E’,‘F’,‘G’,‘H’]层序建立为二叉树,如下图所示。
- 建立二叉树
class Node { // 定义节点
constructor(data){
this.data = data
this.leftChild = null
this.rightChild = null
}
}
const createTree = (arr) => { // 创建二叉树
let tree = new Node(arr[0])
let Nodes = [tree]
let i = 1
for (let node of Nodes){
Nodes.push(node.leftChild = new Node (arr[i]))
i += 1
if (i == arr.length) return tree
Nodes.push(node.rightChild = new Node(arr[i]))
i += 1
if (i == arr.length) return tree
}
}
let datas = ['A','B','C','D','E','F','G','H']
let t = createTree(datas)
console.log(t)
得到结果为:
- 前序遍历
const preOrder = (tree) => { // 前序遍历
if (tree) {
console.log(tree.data)
preOrder(tree.leftChild)
preOrder(tree.rightChild)
}
}
preOrder(t) // A B D H E C F G
- 中序遍历
const midOrder = (tree) => { // 中序遍历
if (tree) {
midOrder(tree.leftChild)
console.log(tree.data)
midOrder(tree.rightChild)
}
}
midOrder(t) // H D B E A F C G
- 后序遍历
const backOrder = (tree) => { // 后序遍历
if (tree) {
backOrder(tree.leftChild)
backOrder(tree.rightChild)
console.log(tree.data)
}
}
backOrder(t) // H D E B F G C A
- 层序遍历(广度优先遍历)
const levelOrder = (tree, nodeList = []) => { // 层序遍历(广度优先)
if (tree) {
nodeList.push(tree)
while (nodeList.length != 0) {
let len = nodeList.length
for (let i = 0; i < len; i++) {
let n = nodeList.shift()
if (n.leftChild) {
nodeList.push(n.leftChild)
}
if (n.rightChild) {
nodeList.push(n.rightChild)
}
console.log(n.data)
}
}
}
}
levelOrder(t) // A B C D E F G H
本文为本人学习总结,如有雷同,可联系本人立即修改或者删除