二叉树的层序遍历 II

二叉树的层序遍历 II

CategoryDifficultyLikesDislikes
algorithmsMedium (72.24%)666-

Tags

tree | breadth-first-search

Companies

Unknown

给你二叉树的根节点 root ,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

示例 1:

1
2
输入:root = [3,9,20,null,null,15,7]
输出:[[15,7],[9,20],[3]]

示例 2:

1
2
输入:root = [1]
输出:[[1]]

示例 3:

1
2
输入:root = []
输出:[]

提示:

  • 树中节点数目在范围 [0, 2000] 内
  • -1000 <= Node.val <= 1000

Discussion | Solution

解法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// @lc code=start
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
    /// ## 解题思路
    /// - 队列
    pub fn level_order_bottom(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
        let mut ret_vec = Vec::new();
        let mut q = VecDeque::new();
        if let Some(root) = root {
            q.push_back(root);
            while !q.is_empty() {
                let mut q_next = VecDeque::new();
                let mut row_vals = Vec::new();
                while let Some(node) = q.pop_front() {
                    row_vals.push(node.borrow().val);
                    if let Some(left) = &node.borrow().left {
                        q_next.push_back(left.clone());
                    }
                    if let Some(right) = &node.borrow().right {
                        q_next.push_back(right.clone());
                    }
                }

                ret_vec.push(row_vals);
                if !q_next.is_empty() {
                    q = q_next;
                }
            }
        }

        ret_vec.reverse();
        ret_vec
    }
}
// @lc code=end
updatedupdated2024-05-152024-05-15