给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3<br /> / \<br /> 9 20<br /> / \<br /> 15 7<br />返回其层序遍历结果:
[
[3],
[9,20],
[15,7]
]
/*** 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[][]}*/var levelOrder = function(root) {const arr = []function travelsal(root, depth) {if (root === null) {return}if (!arr[depth]) {arr[depth] = []}arr[depth].push(root.val)travelsal(root.left, depth + 1)travelsal(root.right, depth + 1)}travelsal(root, 0)return arr};
