1. 广度优先遍历

  • 广度优先遍历出每一层的节点
  • 取每层节点最右的值push到result中
  1. /*
  2. * @lc app=leetcode.cn id=199 lang=javascript
  3. *
  4. * [199] 二叉树的右视图
  5. */
  6. // @lc code=start
  7. /**
  8. * Definition for a binary tree node.
  9. * function TreeNode(val) {
  10. * this.val = val;
  11. * this.left = this.right = null;
  12. * }
  13. */
  14. /**
  15. * @param {TreeNode} root
  16. * @return {number[]}
  17. */
  18. var rightSideView = function (root) {
  19. if (!root) return []
  20. const result = []
  21. const queue = []
  22. queue.push(root)
  23. while (queue.length) {
  24. let len = queue.length
  25. result.push(queue[0].val)
  26. while (len--) {
  27. const node = queue.shift()
  28. if (node.right) queue.push(node.right)
  29. if (node.left) queue.push(node.left)
  30. }
  31. }
  32. return result
  33. }
  34. // @lc code=end

时间复杂度:

  • 每个节点都被遍历到一次所以 时间复杂度为 O(n)

**
空间复杂度:

  • 每个节点最多进队列一次,所以队列长度最大不不超过 nn,所以这里的空间代价为 O(n)


2. 深度优先遍历

  • 根节点开始优先遍历右序列
  • 因为是右序列优先遍历,所以每层的第一个节点就是所能看见的节点
  1. /*
  2. * @lc app=leetcode.cn id=199 lang=javascript
  3. *
  4. * [199] 二叉树的右视图
  5. */
  6. // @lc code=start
  7. /**
  8. * Definition for a binary tree node.
  9. * function TreeNode(val) {
  10. * this.val = val;
  11. * this.left = this.right = null;
  12. * }
  13. */
  14. /**
  15. * @param {TreeNode} root
  16. * @return {number[]}
  17. */
  18. var rightSideView = function (root) {
  19. if (!root) return []
  20. const result = []
  21. DFS(root, 0, result)
  22. return result
  23. }
  24. const DFS = function (node, level, result) {
  25. if (level >= result.length) {
  26. result.push(node.val)
  27. }
  28. level++
  29. if (node.right) DFS(node.right, level, result)
  30. if (node.left) DFS(node.left, level, result)
  31. }
  32. // @lc code=end

时间复杂度:

  • 每个节点都被遍历了一次所以为 O(n)


空间复杂度:**

  • 二叉树的结构未知,最差的情况会退化成一条链表,所以空间复杂度为 O(n)