来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
解答
层级遍历。没啥好说的
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*//*** @param {TreeNode} root* @return {number[][]}*/var levelOrder = function(root) {if (!root) return [];let stack = [root], ret = [];while (stack.length) {let tempStack = [], tempVal = [];for (let item of stack) {item && tempVal.push(item.val);item?.left && tempStack.push(item.left);item?.right && tempStack.push(item.right);}ret.push(tempVal);stack = tempStack;}return ret;};
