File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed
binary-tree-level-order-traversal Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ // Definition for a binary tree node.
2+ // #[derive(Debug, PartialEq, Eq)]
3+ // pub struct TreeNode {
4+ // pub val: i32,
5+ // pub left: Option<Rc<RefCell<TreeNode>>>,
6+ // pub right: Option<Rc<RefCell<TreeNode>>>,
7+ // }
8+ //
9+ // impl TreeNode {
10+ // #[inline]
11+ // pub fn new(val: i32) -> Self {
12+ // TreeNode {
13+ // val,
14+ // left: None,
15+ // right: None
16+ // }
17+ // }
18+ // }
19+ use std:: rc:: Rc ;
20+ use std:: cell:: RefCell ;
21+
22+ #[ derive( Clone ) ]
23+ struct QueueItem {
24+ node : Option < Rc < RefCell < TreeNode > > > ,
25+ dist : i32 ,
26+ }
27+
28+ impl Solution {
29+ pub fn level_order ( root : Option < Rc < RefCell < TreeNode > > > ) -> Vec < Vec < i32 > > {
30+ let mut ans: Vec < Vec < i32 > > = vec ! [ ] ;
31+ let mut queue: Vec < QueueItem > = vec ! [ QueueItem :: new( root, 0 ) ] ;
32+ let mut head = 0 ;
33+ while head != queue. len ( ) { // T(n) = S(n) = O(n)
34+ let u = queue[ head] . clone ( ) ;
35+ head += 1 ;
36+ match u. node {
37+ Some ( v) => {
38+ let v = v. borrow ( ) ;
39+ let v_dist = u. dist + 1 ;
40+ if ans. len ( ) <= u. dist as usize {
41+ ans. push ( vec ! [ ] ) ;
42+ }
43+ let mut a = ans. last_mut ( ) . unwrap ( ) ;
44+ a. push ( v. val ) ;
45+ queue. push ( QueueItem :: new ( v. left . clone ( ) , v_dist) ) ;
46+ queue. push ( QueueItem :: new ( v. right . clone ( ) , v_dist) ) ;
47+ } ,
48+ None => ( ) ,
49+ }
50+ }
51+ ans
52+ }
53+ }
54+
55+ impl QueueItem {
56+ fn new ( node : Option < Rc < RefCell < TreeNode > > > , dist : i32 ) -> Self {
57+ QueueItem {
58+ node : node,
59+ dist : dist,
60+ }
61+ }
62+ }
You can’t perform that action at this time.
0 commit comments