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

二叉树的层序遍历 #299

Open
Sunny-117 opened this issue Nov 8, 2022 · 1 comment
Open

二叉树的层序遍历 #299

Sunny-117 opened this issue Nov 8, 2022 · 1 comment

Comments

@Sunny-117
Copy link
Owner

No description provided.

@lxy-Jason
Copy link
Contributor

var levelOrder = function(root) {
    if(!root) return [];
    let res = [];
    let queue = [root];

    while(queue.length){
        //记录当前层级节点数
        let len = queue.length;
        //存放每一层的节点
        let curLevel = [];
        for(let i = 0; i < len; i++){
            let node = queue.shift();
            curLevel.push(node.val);
            //存入下一层的节点
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
        }
        res.push(curLevel);
    }
    return res;
};

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

2 participants