LeetCode
二叉树的层序遍历 II
107. 二叉树的层序遍历 II - 力扣(LeetCode)
题目描述
给你二叉树的根节点 root
,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[15,7],[9,20],[3]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
- 树中节点数目在范围
[0, 2000]
内 -1000 <= Node.val <= 1000
思路
BFS
代码
C++
class Solution {
public:vector<vector<int>> levelOrderBottom(TreeNode *root) {if (root == nullptr) return {};vector<vector<int>> ans;vector<TreeNode*> cur{root};while (cur.size()) {vector<TreeNode*> nxt;vector<int> vals;for (auto node : cur) {vals.push_back(node->val);if (node->left) nxt.push_back(node->left);if (node->right) nxt.push_back(node->right);}cur = move(nxt);ans.emplace_back(vals);}ranges::reverse(ans);return ans;}
};
Java
class Solution {public List<List<Integer>> levelOrderBottom(TreeNode root) {if (root == null) return List.of();List<List<Integer>> ans = new ArrayList<>();List<TreeNode> cur = List.of(root);while (!cur.isEmpty()) {List<TreeNode> nxt = new ArrayList<>();List<Integer> vals = new ArrayList<>(cur.size()); // 预分配空间for (TreeNode node : cur) {vals.add(node.val);if (node.left != null) nxt.add(node.left);if (node.right != null) nxt.add(node.right);}cur = nxt;ans.add(vals);}Collections.reverse(ans);return ans;}
}