-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path865.cpp
More file actions
67 lines (66 loc) · 2.19 KB
/
865.cpp
File metadata and controls
67 lines (66 loc) · 2.19 KB
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
/**
* 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:
// depth, node contain all deepest tree
pair<int, TreeNode*> dfs(TreeNode* node) {
if (node == nullptr) return make_pair(0, nullptr);
auto left = dfs(node->left);
auto right = dfs(node->right);
int maxDepth = max(left.first, right.first) + 1;
TreeNode* subtree = (left.first == right.first) ? node : (left.first > right.first) ? left.second : right.second;
return make_pair(maxDepth, subtree);
}
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
return dfs(root).second;
}
};
// V2
// class Solution {
// public:
// int maxDepth = 0;
// int count = 0;
// int childrenCount = INT_MAX;
// TreeNode* ans;
// void dfs(TreeNode* node, int depth) {
// if (node == nullptr) return;
// if (depth == maxDepth) {
// count++;
// }
// else if (depth > maxDepth) {
// maxDepth = depth;
// count = 1;
// }
// dfs(node->left, depth + 1);
// dfs(node->right, depth + 1);
// }
// pair<int, int> dfsWithDepthNodes(TreeNode* node, int depth) {
// if (node == nullptr) return make_pair(0, 0);
// int res = (depth == maxDepth) ? 1 : 0;
// auto left = dfsWithDepthNodes(node->left, depth + 1);
// auto right = dfsWithDepthNodes(node->right, depth + 1);
// res += left.first + right.first;
// int nodeCount = left.second + right.second + 1;
// if (res == count) {
// if (nodeCount < childrenCount) {
// childrenCount = nodeCount;
// ans = node;
// }
// }
// return make_pair(res, nodeCount);
// }
// TreeNode* subtreeWithAllDeepest(TreeNode* root) {
// dfs(root, 0);
// dfsWithDepthNodes(root, 0);
// return ans;
// }
// };