1
+ ///
2
+ /// Problem: Binary Tree Level Order Traversal II
3
+ ///
4
+ /// Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values.
5
+ /// (i.e., from left to right, level by level from leaf to root).
6
+ ///
7
+ /// Example 1:
8
+ /// Input: root = [3,9,20,null,null,15,7]
9
+ /// Output: [[15,7],[9,20],[3]]
10
+ ///
11
+ /// Example 2:
12
+ /// Input: root = [1]
13
+ /// Output: [[1]]
14
+ ///
15
+ /// Example 3:
16
+ /// Input: root = []
17
+ /// Output: []
18
+ ///
19
+ /// Constraints:
20
+ /// The number of nodes in the tree is in the range [0, 2000].
21
+ /// -1000 <= Node.val <= 1000
22
+ ///
23
+
24
+ // Definition for a binary tree node (provided by LeetCode)
25
+ // #[derive(Debug, PartialEq, Eq)]
26
+ // pub struct TreeNode {
27
+ // pub val: i32,
28
+ // pub left: Option<Rc<RefCell<TreeNode>>>,
29
+ // pub right: Option<Rc<RefCell<TreeNode>>>,
30
+ // }
31
+ //
32
+ // impl TreeNode {
33
+ // #[inline]
34
+ // pub fn new(val: i32) -> Self {
35
+ // TreeNode {
36
+ // val,
37
+ // left: None,
38
+ // right: None
39
+ // }
40
+ // }
41
+ // }
42
+
43
+ // # Solution :
44
+ // Time complexity: O(n)
45
+ // Space complexity: O(h) - Where h is the height of the tree (for the recursion stack)
46
+ //
47
+
48
+ use std:: rc:: Rc ;
49
+ use std:: cell:: RefCell ;
50
+
51
+ impl Solution {
52
+ pub fn level_order_bottom ( root : Option < Rc < RefCell < TreeNode > > > ) -> Vec < Vec < i32 > > {
53
+ let mut result: Vec < Vec < i32 > > = Vec :: new ( ) ;
54
+ Self :: dfs ( root, 0 , & mut result) ;
55
+ result. reverse ( ) ;
56
+ result
57
+ }
58
+
59
+ fn dfs ( node : Option < Rc < RefCell < TreeNode > > > , level : usize , result : & mut Vec < Vec < i32 > > ) {
60
+ if let Some ( n) = node {
61
+ // Ensure we have a vector for this level
62
+ if result. len ( ) <= level {
63
+ result. push ( Vec :: new ( ) ) ;
64
+ }
65
+
66
+ // Add the current node's value to the appropriate level
67
+ let n_ref = n. borrow ( ) ;
68
+ result[ level] . push ( n_ref. val ) ;
69
+
70
+ // Recursively process left and right subtrees
71
+ Self :: dfs ( n_ref. left . clone ( ) , level + 1 , result) ;
72
+ Self :: dfs ( n_ref. right . clone ( ) , level + 1 , result) ;
73
+ }
74
+ }
75
+ }
0 commit comments