// 二叉树
function Tree(left, label, right) {
this.left = left
this.label = label
this.right = right
}
// 中序遍历
function* inorder(t) {
if(t) {
yield* inorder(t.left)
yield t.label
yield* inorder(t.right)
}
}
function makeTree(array) {
if(array.length === 1) return new Tree(null, array[0], null)
return new Tree(makeTree(array[0]), array[1], makeTree(array[2]))
}
const tree1 = makeTree([
[
['a'], 'b', ['c']
],
'd',
[
['e'], 'f', ['g']
]
])
const tree2 = makeTree([
[
[['h'], 'a', ['i']], 'b', [['j'], 'c', ['k']]
],
'd',
[
['e'], 'f', ['g']
]
])
const a = inorder(tree1)
const b = inorder(tree2)
console.log([...a].join('')) // abcdefg
console.log([...b].join('')) // haibjckdefg
网友评论