-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathFind_Leaves_of_Binary_Tree.cpp
55 lines (54 loc) · 1.77 KB
/
Find_Leaves_of_Binary_Tree.cpp
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
void traverse(TreeNode* node, unordered_map <TreeNode*, unordered_set<TreeNode*> >& adj, queue<TreeNode*>& leaves) {
if(!node) return;
if(!node->left and !node->right) {
leaves.push(node);
return;
}
if(node->left) {
adj[node].insert(node->left);
adj[node->left].insert(node);
traverse(node->left, adj, leaves);
}
if(node->right) {
adj[node].insert(node->right);
adj[node->right].insert(node);
traverse(node->right, adj, leaves);
}
}
public:
vector<vector<int>> findLeaves(TreeNode* root) {
vector<vector<int>> result;
if(!root) return result;
unordered_map <TreeNode*, unordered_set<TreeNode*> > adj;
queue<TreeNode*> leaves;
traverse(root, adj, leaves);
while(!leaves.empty()) {
int k = (int)leaves.size();
vector<int> currLeaves;
while(k--) {
TreeNode* curr = leaves.front();
currLeaves.push_back(curr->val);
for(auto neigh = adj[curr].begin(); neigh != adj[curr].end(); ++neigh) {
adj[*neigh].erase(curr);
if((*neigh == root and adj[*neigh].empty()) or (*neigh != root and adj[*neigh].size() == 1)) {
leaves.push(*neigh);
}
}
adj[curr].clear();
leaves.pop();
}
result.push_back(currLeaves);
}
return result;
}
};