来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

解答

层级遍历。没啥好说的

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */
  8. /**
  9. * @param {TreeNode} root
  10. * @return {number[][]}
  11. */
  12. var levelOrder = function(root) {
  13. if (!root) return [];
  14. let stack = [root], ret = [];
  15. while (stack.length) {
  16. let tempStack = [], tempVal = [];
  17. for (let item of stack) {
  18. item && tempVal.push(item.val);
  19. item?.left && tempStack.push(item.left);
  20. item?.right && tempStack.push(item.right);
  21. }
  22. ret.push(tempVal);
  23. stack = tempStack;
  24. }
  25. return ret;
  26. };