题解 | #求二叉树的层序遍历#

求二叉树的层序遍历

http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */

/**
  * 
  * @param root TreeNode类 
  * @return int整型二维数组
  */
function levelOrder( root ) {
    // write code here
    if(!root) return [];
    let queue = [root];
    let res = [];
    while(queue.length){
        let temp = []
        let queueLength = queue.length;
        while(queueLength) {
            let node = queue.shift();
            node.left && queue.push(node.left);
            node.right && queue.push(node.right)
            queueLength--;
            temp.push(node.val);
        }
        res.push(temp);
    }
    return res
}
module.exports = {
    levelOrder : levelOrder
};
全部评论
res.push(temp) 我想请问一下为为什么里面可以传数组
点赞 回复 分享
发布于 2021-11-09 21:13

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务