1. 广度优先遍历
- 广度优先遍历出每一层的节点
- 取每层节点最右的值push到result中
/*
* @lc app=leetcode.cn id=199 lang=javascript
*
* [199] 二叉树的右视图
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var rightSideView = function (root) {
if (!root) return []
const result = []
const queue = []
queue.push(root)
while (queue.length) {
let len = queue.length
result.push(queue[0].val)
while (len--) {
const node = queue.shift()
if (node.right) queue.push(node.right)
if (node.left) queue.push(node.left)
}
}
return result
}
// @lc code=end
时间复杂度:
- 每个节点都被遍历到一次所以 时间复杂度为 O(n)
**
空间复杂度:
- 每个节点最多进队列一次,所以队列长度最大不不超过 nn,所以这里的空间代价为 O(n)
2. 深度优先遍历
- 根节点开始优先遍历右序列
- 因为是右序列优先遍历,所以每层的第一个节点就是所能看见的节点
/*
* @lc app=leetcode.cn id=199 lang=javascript
*
* [199] 二叉树的右视图
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var rightSideView = function (root) {
if (!root) return []
const result = []
DFS(root, 0, result)
return result
}
const DFS = function (node, level, result) {
if (level >= result.length) {
result.push(node.val)
}
level++
if (node.right) DFS(node.right, level, result)
if (node.left) DFS(node.left, level, result)
}
// @lc code=end
时间复杂度:
- 每个节点都被遍历了一次所以为 O(n)
空间复杂度:**
- 二叉树的结构未知,最差的情况会退化成一条链表,所以空间复杂度为 O(n)