File tree 1 file changed +53
-5
lines changed
binary_tree_level_order_traveral/src
1 file changed +53
-5
lines changed Original file line number Diff line number Diff line change 1
- #[ cfg( test) ]
2
- mod tests {
3
- #[ test]
4
- fn it_works ( ) {
5
- assert_eq ! ( 2 + 2 , 4 ) ;
1
+ /*!
2
+ * https://leetcode.com/explore/challenge/card/may-leetcoding-challenge-2021/600/week-3-may-15th-may-21st/3749/
3
+ */
4
+
5
+ use std:: cell:: RefCell ;
6
+ use std:: rc:: Rc ;
7
+
8
+ // Definition for a binary tree node.
9
+ #[ derive( Debug , PartialEq , Eq ) ]
10
+ pub struct TreeNode {
11
+ pub val : i32 ,
12
+ pub left : Option < Rc < RefCell < TreeNode > > > ,
13
+ pub right : Option < Rc < RefCell < TreeNode > > > ,
14
+ }
15
+
16
+ impl TreeNode {
17
+ #[ inline]
18
+ pub fn new ( val : i32 ) -> Self {
19
+ TreeNode {
20
+ val,
21
+ left : None ,
22
+ right : None ,
23
+ }
24
+ }
25
+ }
26
+
27
+ pub struct Solution { }
28
+
29
+ impl Solution {
30
+ pub fn level_order ( root : Option < Rc < RefCell < TreeNode > > > ) -> Vec < Vec < i32 > > {
31
+ match root {
32
+ None => vec ! [ ] ,
33
+ Some ( rt) => {
34
+ let mut left = Self :: level_order ( rt. borrow ( ) . left . clone ( ) ) ;
35
+ let mut right = Self :: level_order ( rt. borrow ( ) . right . clone ( ) ) ;
36
+ let mut result = vec ! [ ] ;
37
+ for i in 0 ..left. len ( ) . max ( right. len ( ) ) + 1 {
38
+ result. push ( vec ! [ ] ) ;
39
+ if i == 0 {
40
+ result[ i] . push ( rt. borrow ( ) . val ) ;
41
+ continue ;
42
+ }
43
+ let j = i - 1 ;
44
+ if j < left. len ( ) {
45
+ result[ i] . append ( & mut left[ j] ) ;
46
+ }
47
+ if j < right. len ( ) {
48
+ result[ i] . append ( & mut right[ j] ) ;
49
+ }
50
+ }
51
+ result
52
+ }
53
+ }
6
54
}
7
55
}
You can’t perform that action at this time.
0 commit comments