题目

从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,15,7]
提示:
节点总数 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

1.BFS

  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. //层序遍历
  14. const queue = [root]
  15. const res = []
  16. while (queue.length > 0) {
  17. const node = queue.pop()
  18. if (node) {
  19. res.push(node.val)
  20. }
  21. if (node && node.left) {
  22. queue.unshift(node.left)
  23. }
  24. if (node && node.right) {
  25. queue.unshift(node.right)
  26. }
  27. }
  28. return res
  29. };