leetcode 102. 二叉树的层次遍历

mac2024-03-31  26

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如: 给定二叉树: [3,9,20,null,null,15,7],

3 / \ 9 20 / \ 15 7

返回其层次遍历结果:

[ [3], [9,20], [15,7] ] /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number[][]} */ var a = { val: 3, left: { val: 9, left: { val: 15, }, right: { val: 7, } }, right: { val: 20, left: { val: 15, }, right: { val: 7, } } } var levelOrder = function (root) { var result = [] // bfc var queue = [] if (root != null) { queue.push(root) } while (queue.length != 0) { console.log(queue) var cenlength = queue.length var vec_temp = [] while (cenlength--) { root = queue.shift() console.log(root) vec_temp.push(root.val) if (root.left) { queue.push(root.left) } if (root.right) { queue.push(root.right) } } result.push(vec_temp) } return result }; console.log(levelOrder(a))

 

最新回复(0)