leetcode 199题 二叉树的右视图
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例 1:
输入: [1,2,3,null,5,null,4]
输出: [1,3,4]
示例 2:
输入: [1,null,3]
输出: [1,3]
示例 3:
输入: []
输出: []
思路
bfs
代码
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
function rightSideView(root) {
if (root === null) {
return [];
}
const queue = [root];
let temp = [];
const res = [];
let curNum = 1;
let nextNum = 0;
while (queue.length !== 0) {
if (curNum > 0) {
const node = queue.shift();
if (node.left) {
queue.push(node.left);
nextNum++;
}
if (node.right) {
queue.push(node.right);
nextNum++;
}
curNum--;
temp.push(node.val);
}
if (curNum === 0) {
res.push(temp[temp.length-1]);
curNum = nextNum;
nextNum = 0;
temp = [];
}
}
return res;
}
复杂度分析
- 时间复杂度:O(N)
- 空间复杂度:O(N)
FEATURED TAGS
前端开发
H5
JavaScript
设计模式
browser
jQuery
源码分析
生活
leetcode
Array
Stack
Queue
Linked List
剑指offer
Binary Search Tree
Binary Tree
Breadth-First Search
Depth-First Search
String
Set
Binary Search
Sliding Window
Backtracking
Dynamic Programming
Two Pointers
Union Find
Sort
Bit Operation
Recursion
Map
Graph
Search
Hash
LinkedList
复盘
QuickSort
Trie
Design
MinHeap
Traverse
Min Heap
Node.js
BackEnd
SQL
MySQL
Design Patterns
Network
计算机网络
Python
SVG