-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcousinsInBinaryTree.cpp
More file actions
51 lines (48 loc) · 1.32 KB
/
Copy pathcousinsInBinaryTree.cpp
File metadata and controls
51 lines (48 loc) · 1.32 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
/**
* https://leetcode.com/problems/cousins-in-binary-tree/
* Tree, DFS, BFS, Binary Tree
* Easy
*/
#include <iostream>
using namespace std;
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:
pair<int, TreeNode*> findDepthAndParent(TreeNode* root, int target, int depth, TreeNode* parent) {
if (!root) {
return make_pair(-1, nullptr);
}
if (root->val == target) {
return make_pair(depth, parent);
}
auto leftResult = findDepthAndParent(root->left, target, depth + 1, root);
if (leftResult.first != -1) {
return leftResult;
}
return findDepthAndParent(root->right, target, depth + 1, root);
}
bool isCousins(TreeNode* root, int x, int y) {
auto xInfo = findDepthAndParent(root, x, 0, nullptr);
auto yInfo = findDepthAndParent(root, y, 0, nullptr);
return (xInfo.first == yInfo.first) && (xInfo.second != yInfo.second);
}
};
int main() {
TreeNode* root;
int x, y;
cout << "Input both nodes: ";
cin >> x >> y;
Solution solution;
if (solution.isCousins(root, x, y)) {
cout << "cousins" << endl;
} else {
cout << "not cousins" << endl;
}
}