比較的完全なバイナリ ツリー構造は次のとおりです。
前順序の走査結果: abdecfg
中間順序の走査結果: dbeafcg
後続の走査結果: debfgca
バイナリツリーを構築する
function NodeTree(value) {
this.value = value
this.left = null
this.right = null
}
let ta = new NodeTree('a'),
tb = new NodeTree('b'),
tc = new NodeTree('c'),
td = new NodeTree('d'),
te = new NodeTree('e'),
tf = new NodeTree('f'),
tg = new NodeTree('g');
ta.left = tb;
ta.right = tc;
tb.left = td;
tb.right = te;
tc.left = tf;
tc.right = tg;
方法 1: 再帰
// 保存遍历的结果
let tF = [], tM = [], tE = []
// 前序
function treeFront(root) {
if (!root || root.value === null) {
return null
}
tF.push(root.value)
treeFront(root.left)
treeFront(root.right)
return tF
}
// 中序
function treeMiddle(root) {
if (!root || root.value === null) {
return null
}
treeMiddle(root.left)
tM.push(root.value)
treeMiddle(root.right)
return tM
}
// 后序
function treeEnd(root) {
if (!root || root.value === null) {
return null
}
treeEnd(root.left)
treeEnd(root.right)
tE.push(root.value)
return tE
}
// test
console.log("前序: ", treeFront(ta)); // ['a', 'b', 'd', 'e', 'c', 'f', 'g']
console.log("中序: ", treeMiddle(ta)); // ['d', 'b', 'e', 'a', 'f', 'c', 'g']
console.log("后序: ", treeEnd(ta)); // ['d', 'e', 'b', 'f', 'g', 'c', 'a']
方法 2: 非再帰的
// 前序
function preorderTraversal(root) {
const stack = [], result = []
root && stack.push(root)
while (stack.length > 0) {
let curNode = stack.pop()
if (curNode !== null) {
result.push(curNode.value)
curNode && stack.push(curNode.right)
curNode && stack.push(curNode.left)
}
}
return result
}
// 中序
function inorderTraversal(root) {
const stack = [], result = []
let node = root
while (stack.length > 0 || node !== null) {
if (node) {
stack.push(node)
node = node.left
} else {
node = stack.pop()
result.push(node.value)
node = node.right
}
}
return result
}
// 后序
function postorderTraversal(root) {
const stack = [], result = []
while (root || stack.length) {
result.unshift(root.value)
root.left && stack.push(root.left)
root.right && stack.push(root.right)
root = stack.pop()
}
return result
}
// test
console.log("前序: ", preorderTraversal(ta)); // ['a', 'b', 'd', 'e', 'c', 'f', 'g']
console.log("中序: ", inorderTraversal(ta)); // ['d', 'b', 'e', 'a', 'f', 'c', 'g']
console.log("后序: ", postorderTraversal(ta)); // ['d', 'e', 'b', 'f', 'g', 'c', 'a']