码迷,mamicode.com
首页 > 编程语言 > 详细

js算法之树的遍历

时间:2019-01-24 00:27:14      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:形状   struct   tran   his   执行   tree   cto   const   中序   

假如树的形状如下所示:

    class Tree {
        constructor(v,children) {
            this.v = v
            this.children = children || null
        }
    }
    const tree = new Tree(10,[
        new Tree(5),
        new Tree(3,[
            new Tree(7),
            new Tree(11,[
                new Tree(3),
                new Tree(2)
            ])
        ]),
        new Tree(2)
    ])

先序

    function tree_transersef(tree) {
        console.log(tree.v)
        // forEach里面可以直接跟函数,就直接和递归连用了,这种写法写起来比较省事
        tree.children && tree.children.forEach(tree_transersef)
    }
    tree_transersef(tree) //10 5 3 7 11 3 2 2

 

后序

    function tree_transverse_l(tree) {
        tree.children && tree.children.forEach(tree_transverse_l)
        // 如果树有孩子就把它的孩子都遍历完之后再来把tree.v打出来
        console.log(tree.v)
    }
    tree_transverse_l(tree) // 5 7 3 2 11 3 2 10

中序

    function tree_transverse_m(tree,ord = 0) {
        let transversed = false
        if(!tree.children) {
            console.log(tree.v)
            return
        }
        tree.children.forEach((child,i) => {
            if(i === ord ) {
               transversed = true
               console.log(tree.v) 
            }
            tree_transverse_m(child,ord)
        });
        // 这里和上面的先序或者后序是同样的道理,主要是看父级tree在遍历的时候前面有没有打出来过->
        // 如果打出来过了,就不执行了,如果没有打出来过,就执行
        !transversed && console.log(tree.v)
    }

回调

    function tree_transverse(tree,ord = 0,callback) {
        let transversed = false
        if(!tree.children) {
            callback(tree.v)
            return
        }
        tree.children.forEach((child,i) => {
            if(i === ord ) {
               transversed = true
               callback(tree.v) 
            }
            tree_transverse_m(child,ord)
        });
        !transversed && callback(tree.v)
    }

基于Generator(相比于forEach在循环的时候可以break)

    function* tree_transverse(tree,ord=0) {
        let transversed = false
        if(!tree.children) {
            yield tree
            return
        }
        for(let i =0;i < tree.children.length;i++) {
            if(i === ord) {
                transversed = true
                yield tree
            }
            yield *tree_transverse(tree.children[i],ord)
        }
        if(!transversed) {
            yield tree
        }
    }
    console.log([...tree_transverse(tree)],‘test‘)

 

js算法之树的遍历

标签:形状   struct   tran   his   执行   tree   cto   const   中序   

原文地址:https://www.cnblogs.com/fanzhanxiang/p/10312068.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!