107. Binary Tree Level Order Traversal II
Medium
Given the root
of a binary tree, return the bottom-up level order traversal of its nodes’ values. (i.e., from left to right, level by level from leaf to root).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range
[0, 2000]
. -1000 <= Node.val <= 1000
思路
用一个数组 next_treenode_vec 存放下一个循环访问的树节点。(循环外初始化时存放根节点)
在每个循环中,
- 更新 current_treenode_vec 使其指向 next_treenode_vec。
- next_treenode_vec 指向一个新数组。
- 将 current_treenode_vec 中每一个节点左右儿子加入 next_treenode_vec;
- 将 current_treenode_vec 中每一个节点的值存入 reversed_result。
若一个循环结束后 next_treenode_vec 仍为空,说明无新节点需要处理,终止循环。
将 reversed_result 翻转返回。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
if (root == nullptr) return vector<vector<int>>();
vector<vector<int>> reversed_result;
vector<TreeNode*> *next_treenode_vec = new vector<TreeNode*>(1, root);
vector<TreeNode*> *current_treenode_vec;
while (!next_treenode_vec->empty()) {
current_treenode_vec = next_treenode_vec;
next_treenode_vec = new vector<TreeNode*>();
vector<int> *current_val_vec = new vector<int>();
for (auto p_treenode : *current_treenode_vec) {
if (p_treenode->left != nullptr){
next_treenode_vec->emplace_back(p_treenode->left);
}
if (p_treenode->right != nullptr){
next_treenode_vec->emplace_back(p_treenode->right);
}
current_val_vec->emplace_back(p_treenode->val);
}
delete current_treenode_vec;
reversed_result.emplace_back(move(*current_val_vec));
}
delete next_treenode_vec;
reverse(reversed_result.begin(), reversed_result.end());
return reversed_result;
}
};
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Binary Tree Level Order Traversal II.
Memory Usage: 12.4 MB, less than 94.23% of C++ online submissions for Binary Tree Level Order Traversal II.