[LeetCode] Binary Tree Level Order Traversal II

107. Binary Tree Level Order Traversal II

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).

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
/**
* 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 {
vector<vector<int>> res;
void helper(TreeNode* node, int level = 0) {
if(!node) return;
if(res.size() <= level) res.emplace_back();
res[level].push_back(node->val);
helper(node->left, level + 1);
helper(node->right, level + 1);
}
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
helper(root);

reverse(begin(res), end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/02/PS/LeetCode/binary-tree-level-order-traversal-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.