晴明的博客园 GitHub      CodePen      CodeWars     

[js] 多叉树

  • 树形结构数据
    var treeNodes = [
        {
            id: 1,
            name: '1',
            children: [
                {
                    id: 11,
                    name: '11',
                    children: [
                        {
                            id: 111,
                            name: '111',
                            children: []
                        },
                        {
                            id: 112,
                            name: '112'
                        }
                    ]
                },
                {
                    id: 12,
                    name: '12',
                    children: []
                }
            ],
            users: []
        },
        {
            id: 2,
            name: '2',
            children: [
                {
                    id: 22,
                    name: '22',
                    children: []
                }
            ]
        }
    ];

递归

//return一般适用单层纵深遍历

    let str = '';
    function parseTreeJson(data) {
        for (let v of data) {
            str += `${v.id}->`;
            let childs = v.children;
            if (childs && childs.length) {
                parseTreeJson(childs);
            }
        }
    }
	
    parseTreeJson(treeNodes)
    console.log(str)//1->11->111->112->12->2->22->

非递归广度优先实现

    let str = '';
    function iterator(data) {
        let stack = [];
        //先将第一层节点放入栈
        for (let v of data) {
            stack.push(v);
        }
        let item;
        while (stack.length) {
            item = stack.shift();
            str += `${item.id}->`;
            //如果该节点有子节点,继续添加进入栈底
            if (item.children && item.children.length) {
                // for (let v of item.children) {
                //  stack.push(v);
                // }
                stack = stack.concat(item.children);
            }
        }
    }
	
    iterator(treeNodes);
    console.log(str)//1->2->11->12->22->111->112->

非递归深度优先实现

    let str = '';
    function iterator(data) {
        let stack = [];
        //先将第一层节点放入栈
        for (let v of data) {
            stack.push(v);
        }
        let item;
        while (stack.length) {
            item = stack.shift();
            str += `${item.id}->`;
            //如果该节点有子节点,继续添加进入栈顶
            if (item.children && item.children.length) {
                //for (let v of item.children) {
                //    stack.unshift(v);
                //}
                stack = (item.children).concat(stack);
            }
        }
    }
	
    iterator(treeNodes);
    console.log(str)//1->11->111->112->12->2->22->
posted @ 2017-03-15 22:50  晴明桑  阅读(496)  评论(0编辑  收藏  举报