8080
8181### 方法一:BFS
8282
83- 使用 BFS 层序遍历二叉树,每层最后一个节点即为该层的右视图节点 。
83+ 我们可以使用广度优先搜索,定义一个队列 $\textit{q}$,将根节点放入队列中。每次从队列中取出当前层的所有节点,对于当前节点,我们先判断右子树是否存在,若存在则将右子树放入队列中;再判断左子树是否存在,若存在则将左子树放入队列中。这样每次取出队列中的第一个节点即为该层的右视图节点 。
8484
8585时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树节点个数。
8686
@@ -102,13 +102,13 @@ class Solution:
102102 return ans
103103 q = deque([root])
104104 while q:
105- ans.append(q[- 1 ].val)
105+ ans.append(q[0 ].val)
106106 for _ in range (len (q)):
107107 node = q.popleft()
108- if node.left:
109- q.append(node.left)
110108 if node.right:
111109 q.append(node.right)
110+ if node.left:
111+ q.append(node.left)
112112 return ans
113113```
114114
@@ -139,15 +139,15 @@ class Solution {
139139 Deque<TreeNode > q = new ArrayDeque<> ();
140140 q. offer(root);
141141 while (! q. isEmpty()) {
142- ans. add(q. peekLast (). val);
143- for (int n = q. size(); n > 0 ; -- n ) {
142+ ans. add(q. peekFirst (). val);
143+ for (int k = q. size(); k > 0 ; -- k ) {
144144 TreeNode node = q. poll();
145- if (node. left != null ) {
146- q. offer(node. left);
147- }
148145 if (node. right != null ) {
149146 q. offer(node. right);
150147 }
148+ if (node. left != null ) {
149+ q. offer(node. left);
150+ }
151151 }
152152 }
153153 return ans;
@@ -177,17 +177,17 @@ public:
177177 return ans;
178178 }
179179 queue<TreeNode* > q{{root}};
180- while (!q.empty ()) {
181- ans.emplace_back (q.back ()->val);
182- for (int n = q.size(); n ; --n ) {
183- TreeNode * node = q.front();
180+ while (q.size ()) {
181+ ans.push_back (q.front ()->val);
182+ for (int k = q.size(); k ; --k ) {
183+ auto node = q.front();
184184 q.pop();
185- if (node->left) {
186- q.push(node->left);
187- }
188185 if (node->right) {
189186 q.push(node->right);
190187 }
188+ if (node->left) {
189+ q.push(node->left);
190+ }
191191 }
192192 }
193193 return ans;
@@ -212,16 +212,16 @@ func rightSideView(root *TreeNode) (ans []int) {
212212 }
213213 q := []*TreeNode{root}
214214 for len(q) > 0 {
215- ans = append(ans, q[len(q)-1 ].Val)
216- for n := len(q); n > 0; n -- {
215+ ans = append(ans, q[0 ].Val)
216+ for k := len(q); k > 0; k -- {
217217 node := q[0]
218218 q = q[1:]
219- if node.Left != nil {
220- q = append(q, node.Left)
221- }
222219 if node.Right != nil {
223220 q = append(q, node.Right)
224221 }
222+ if node.Left != nil {
223+ q = append(q, node.Left)
224+ }
225225 }
226226 }
227227 return
@@ -246,23 +246,24 @@ func rightSideView(root *TreeNode) (ans []int) {
246246 */
247247
248248function rightSideView(root : TreeNode | null ): number [] {
249+ const ans: number [] = [];
249250 if (! root ) {
250- return [] ;
251+ return ans ;
251252 }
252- let q = [root ];
253- const ans: number [] = [];
254- while (q .length ) {
255- const nextq: TreeNode [] = [];
256- ans .push (q .at (- 1 )! .val );
253+ const q: TreeNode [] = [root ];
254+ while (q .length > 0 ) {
255+ ans .push (q [0 ].val );
256+ const nq: TreeNode [] = [];
257257 for (const { left, right } of q ) {
258- if (left ) {
259- nextq .push (left );
260- }
261258 if (right ) {
262- nextq .push (right );
259+ nq .push (right );
260+ }
261+ if (left ) {
262+ nq .push (left );
263263 }
264264 }
265- q = nextq ;
265+ q .length = 0 ;
266+ q .push (... nq );
266267 }
267268 return ans ;
268269}
@@ -294,32 +295,71 @@ use std::collections::VecDeque;
294295use std :: rc :: Rc ;
295296impl Solution {
296297 pub fn right_side_view (root : Option <Rc <RefCell <TreeNode >>>) -> Vec <i32 > {
297- let mut res = vec! [];
298+ let mut ans = vec! [];
298299 if root . is_none () {
299- return res ;
300+ return ans ;
300301 }
301302 let mut q = VecDeque :: new ();
302303 q . push_back (root );
303304 while ! q . is_empty () {
304- let n = q . len ();
305- res . push (q [n - 1 ]. as_ref (). unwrap (). borrow (). val);
306- for _ in 0 .. n {
305+ let k = q . len ();
306+ ans . push (q [0 ]. as_ref (). unwrap (). borrow (). val);
307+ for _ in 0 .. k {
307308 if let Some (node ) = q . pop_front (). unwrap () {
308309 let mut node = node . borrow_mut ();
309- if node . left. is_some () {
310- q . push_back (node . left. take ());
311- }
312310 if node . right. is_some () {
313311 q . push_back (node . right. take ());
314312 }
313+ if node . left. is_some () {
314+ q . push_back (node . left. take ());
315+ }
315316 }
316317 }
317318 }
318- res
319+ ans
319320 }
320321}
321322```
322323
324+ #### JavaScript
325+
326+ ``` js
327+ /**
328+ * Definition for a binary tree node.
329+ * function TreeNode(val, left, right) {
330+ * this.val = (val===undefined ? 0 : val)
331+ * this.left = (left===undefined ? null : left)
332+ * this.right = (right===undefined ? null : right)
333+ * }
334+ */
335+ /**
336+ * @param {TreeNode} root
337+ * @return {number[]}
338+ */
339+ var rightSideView = function (root ) {
340+ const ans = [];
341+ if (! root) {
342+ return ans;
343+ }
344+ const q = [root];
345+ while (q .length > 0 ) {
346+ ans .push (q[0 ].val );
347+ const nq = [];
348+ for (const { left , right } of q) {
349+ if (right) {
350+ nq .push (right);
351+ }
352+ if (left) {
353+ nq .push (left);
354+ }
355+ }
356+ q .length = 0 ;
357+ q .push (... nq);
358+ }
359+ return ans;
360+ };
361+ ```
362+
323363<!-- tabs: end -->
324364
325365<!-- solution: end -->
@@ -345,13 +385,13 @@ impl Solution {
345385# self.right = right
346386class Solution :
347387 def rightSideView (self , root : Optional[TreeNode]) -> List[int ]:
348- def dfs (node , depth ) :
349- if node is None :
388+ def dfs (root : Optional[TreeNode] , depth : int ) -> None :
389+ if root is None :
350390 return
351- if depth == len (ans):
352- ans.append(node .val)
353- dfs(node .right, depth + 1 )
354- dfs(node .left, depth + 1 )
391+ if len (ans) == depth :
392+ ans.append(root .val)
393+ dfs(root .right, depth + 1 )
394+ dfs(root .left, depth + 1 )
355395
356396 ans = []
357397 dfs(root, 0 )
@@ -384,15 +424,15 @@ class Solution {
384424 return ans;
385425 }
386426
387- private void dfs (TreeNode node , int depth ) {
388- if (node == null ) {
427+ private void dfs (TreeNode root , int depth ) {
428+ if (root == null ) {
389429 return ;
390430 }
391- if (depth == ans. size()) {
392- ans. add(node . val);
431+ if (ans. size() == depth ) {
432+ ans. add(root . val);
393433 }
394- dfs(node . right, depth + 1 );
395- dfs(node . left, depth + 1 );
434+ dfs(root . right, depth + 1 );
435+ dfs(root . left, depth + 1 );
396436 }
397437}
398438```
@@ -415,15 +455,15 @@ class Solution {
415455public:
416456 vector<int > rightSideView(TreeNode* root) {
417457 vector<int > ans;
418- function<void(TreeNode * , int)> dfs = [ &] (TreeNode* node , int depth) {
419- if (!node ) {
458+ auto dfs = [ &] (this auto&& dfs, TreeNode* root , int depth) -> void {
459+ if (!root ) {
420460 return;
421461 }
422- if (depth == ans.size()) {
423- ans.emplace_back(node ->val);
462+ if (ans.size() == depth ) {
463+ ans.push_back(root ->val);
424464 }
425- dfs(node ->right, depth + 1);
426- dfs(node ->left, depth + 1);
465+ dfs(root ->right, depth + 1);
466+ dfs(root ->left, depth + 1);
427467 };
428468 dfs(root, 0);
429469 return ans;
@@ -444,15 +484,15 @@ public:
444484 */
445485func rightSideView(root *TreeNode) (ans []int) {
446486 var dfs func(*TreeNode, int)
447- dfs = func(node *TreeNode, depth int) {
448- if node == nil {
487+ dfs = func(root *TreeNode, depth int) {
488+ if root == nil {
449489 return
450490 }
451- if depth == len(ans) {
452- ans = append(ans, node .Val)
491+ if len(ans) == depth {
492+ ans = append(ans, root .Val)
453493 }
454- dfs(node .Right, depth+1)
455- dfs(node .Left, depth+1)
494+ dfs(root .Right, depth+1)
495+ dfs(root .Left, depth+1)
456496 }
457497 dfs(root, 0)
458498 return
@@ -478,21 +518,95 @@ func rightSideView(root *TreeNode) (ans []int) {
478518
479519function rightSideView(root : TreeNode | null ): number [] {
480520 const ans = [];
481- const dfs = (node : TreeNode | null , depth : number ) => {
482- if (! node ) {
521+ const dfs = (root : TreeNode | null , depth : number ) => {
522+ if (! root ) {
483523 return ;
484524 }
485- if (depth == ans . length ) {
486- ans .push (node .val );
525+ if (ans . length == depth ) {
526+ ans .push (root .val );
487527 }
488- dfs (node .right , depth + 1 );
489- dfs (node .left , depth + 1 );
528+ dfs (root .right , depth + 1 );
529+ dfs (root .left , depth + 1 );
490530 };
491531 dfs (root , 0 );
492532 return ans ;
493533}
494534```
495535
536+ #### Rust
537+
538+ ``` rust
539+ // Definition for a binary tree node.
540+ // #[derive(Debug, PartialEq, Eq)]
541+ // pub struct TreeNode {
542+ // pub val: i32,
543+ // pub left: Option<Rc<RefCell<TreeNode>>>,
544+ // pub right: Option<Rc<RefCell<TreeNode>>>,
545+ // }
546+ //
547+ // impl TreeNode {
548+ // #[inline]
549+ // pub fn new(val: i32) -> Self {
550+ // TreeNode {
551+ // val,
552+ // left: None,
553+ // right: None
554+ // }
555+ // }
556+ // }
557+ use std :: cell :: RefCell ;
558+ use std :: rc :: Rc ;
559+ impl Solution {
560+ pub fn right_side_view (root : Option <Rc <RefCell <TreeNode >>>) -> Vec <i32 > {
561+ let mut ans = Vec :: new ();
562+ fn dfs (node : Option <Rc <RefCell <TreeNode >>>, depth : usize , ans : & mut Vec <i32 >) {
563+ if let Some (node_ref ) = node {
564+ let node = node_ref . borrow ();
565+ if ans . len () == depth {
566+ ans . push (node . val);
567+ }
568+ dfs (node . right. clone (), depth + 1 , ans );
569+ dfs (node . left. clone (), depth + 1 , ans );
570+ }
571+ }
572+ dfs (root , 0 , & mut ans );
573+ ans
574+ }
575+ }
576+ ```
577+
578+ #### JavaScript
579+
580+ ``` js
581+ /**
582+ * Definition for a binary tree node.
583+ * function TreeNode(val, left, right) {
584+ * this.val = (val===undefined ? 0 : val)
585+ * this.left = (left===undefined ? null : left)
586+ * this.right = (right===undefined ? null : right)
587+ * }
588+ */
589+ /**
590+ * @param {TreeNode} root
591+ * @return {number[]}
592+ */
593+ var rightSideView = function (root ) {
594+ const ans = [];
595+ const dfs = (root , depth ) => {
596+ if (! root) {
597+ return ;
598+ }
599+ if (ans .length == depth) {
600+ ans .push (root .val );
601+ }
602+ dfs (root .right , depth + 1 );
603+ dfs (root .left , depth + 1 );
604+ };
605+ dfs (root, 0 );
606+ return ans;
607+ };
608+ ```
609+
496610<!-- tabs: end -->
497611
498612<!-- solution: end -->
0 commit comments