-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path650.find-leaves-of-binary-tree.cpp
109 lines (99 loc) · 2.51 KB
/
650.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Tag: Binary Tree, Depth First Search/DFS, Divide and Conquer
// Time: O(N)
// Space: O(N)
// Ref: Leetcode-366
// Note: -
// Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
//
// **Example1**
// Input: {1,2,3,4,5}
// Output: `[[4, 5, 3], [2], [1]]`.
// Explanation:
// ```
// 1
// / \
// 2 3
// / \
// 4 5
// ```
//
// **Example2**
// Input: {1,2,3,4}
// Output: `[[4, 3], [2], [1]]`.
// Explanation:
// ```
// 1
// / \
// 2 3
// /
// 4
// ```
//
//
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param root: the root of binary tree
* @return: collect and remove all leaves
*/
vector<vector<int>> findLeaves(TreeNode * root) {
// write your code here
unordered_map<int, vector<int>> cache;
vector<vector<int>> res;
findReverseHeight(root, cache);
int height = 0;
while (cache.count(height) > 0) {
res.push_back(cache[height]);
height += 1;
}
return res;
}
int findReverseHeight(TreeNode * root, unordered_map<int, vector<int>>& cache) {
if (!root) {
return -1;
}
int lh = findReverseHeight(root->left, cache);
int rh = findReverseHeight(root->right, cache);
int height = max(lh, rh) + 1;
cache[height].push_back(root->val);
return height;
}
};
class Solution {
public:
/*
* @param root: the root of binary tree
* @return: collect and remove all leaves
*/
vector<vector<int>> findLeaves(TreeNode * root) {
// write your code here
vector<vector<int>> res;
findReverseHeight(root, res);
return res;
}
int findReverseHeight(TreeNode * root, vector<vector<int>>& res) {
if (!root) {
return -1;
}
int lh = findReverseHeight(root->left, res);
int rh = findReverseHeight(root->right, res);
int height = max(lh, rh) + 1;
if (height >= res.size()) {
res.push_back({});
}
res[height].push_back(root->val);
return height;
}
};