美文网首页
js二叉树中序遍历

js二叉树中序遍历

作者: sorry510 | 来源:发表于2019-12-20 13:44 被阅读0次
// 二叉树
    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

相关文章

网友评论

      本文标题:js二叉树中序遍历

      本文链接:https://www.haomeiwen.com/subject/egtinctx.html