-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem-107.cpp
More file actions
29 lines (24 loc) · 754 Bytes
/
Copy pathProblem-107.cpp
File metadata and controls
29 lines (24 loc) · 754 Bytes
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
// Problem - 107
// https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
// O(n) time complexity and O(n) space complexity solution using dfs
class Solution {
public:
int height(TreeNode* root) {
if(!root)
return 0;
return max(height(root->left), height(root->right)) + 1;
}
void dfs(TreeNode* root, int lvl, vector <vector<int>> &v, int h) {
if(!root)
return;
v[h - lvl].push_back(root->val);
dfs(root->left, lvl+1, v, h);
dfs(root->right, lvl+1, v, h);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
int h = height(root);
vector <vector<int>> v(h);
dfs(root, 0, v, --h);
return v;
}
};