给你二叉树的根节点 root
,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number[][]} */ const levelOrder = (root) => { const res = [] if (!root) return res const queue = [] queue.push(root) while (queue.length) { res.push([]) let len = queue.length for (let i = 0; i < len; i++) { const node = queue.shift() res[res.length - 1].push(node.val) if (node.left) { queue.push(node.left) } if (node.right) { queue.push(node.right) } } } return res };
标签:node,遍历,val,res,层序,queue,right,二叉树,left From: https://www.cnblogs.com/zhenjianyu/p/17110196.html