Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

非递归的方式实现树的广度与深度优先遍历 #9

Open
Diazhao opened this issue Aug 6, 2019 · 0 comments
Open

非递归的方式实现树的广度与深度优先遍历 #9

Diazhao opened this issue Aug 6, 2019 · 0 comments

Comments

@Diazhao
Copy link
Owner

Diazhao commented Aug 6, 2019

let tree = {
    a: {
        b: {
            c: {
                d: 11,
                e: 11,
                f: 11
            },
            g: {
                h: 11
            },
            i: {
                j: 66,
                k: 77
            }
        },
        l: 23
    },
    m: {
        n: {
            o: 11,
            p: 11
        },
        q: 11
    },
    r: 12,
    s: 13
}


/**
 * @description 深度优先遍历,压入栈之后,以此弹出,弹出一个,重新压入新节点的node
 * @param {} tr 
 */
function deepLoop(tr){
    var stack = [];
    if(null !== tr){
        stack.push(tr);
        while(stack.length > 0){
            let node = stack.pop();
            console.log(node);
            if(typeof node === 'object'){
                let keys = Object.keys(node);
                for(let i=0; i< keys.length; i++){
                    stack.push(node[keys[i]])
                }
            }
        }
    }
}

/**
 * @description 树的广度优先遍历, 与深度优先的区别就在于出栈的时机不同
 * @param {} tr 
 */
function guangduLoop(tr){
    var stack = [];
    if(null !== tr){
        stack.push(tr);
        while(stack.length > 0){
            let node = stack.shift();
            console.log(node);
            if(typeof node === 'object'){
                let keys = Object.keys(node);
                for(let i=0; i< keys.length; i++){
                    stack.push(node[keys[i]])
                }
            }
        }
    }
}

guangduLoop(tree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant