|
| 1 | +#include<vector> |
| 2 | +#include<algorithm> |
| 3 | +#include<iostream> |
| 4 | +#include<unordered_map> |
| 5 | +using namespace std; |
| 6 | +/** |
| 7 | +* Definition for a binary tree node. |
| 8 | +*/ |
| 9 | +struct TreeNode { |
| 10 | +int val; |
| 11 | +TreeNode *left; |
| 12 | +TreeNode *right; |
| 13 | +TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 14 | +TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 15 | +TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 16 | +}; |
| 17 | + |
| 18 | +class Solution { |
| 19 | +public: |
| 20 | +bool isCousins(TreeNode* root, int x, int y) { |
| 21 | +unordered_map<int, int> depths; /* map: value -> depth */ |
| 22 | +unordered_map<int, int> parents; /* map: value -> parent value */ |
| 23 | +dfs(root, 0, depths, parents); |
| 24 | +if (depths[x] == depths[y] && parents[x] != parents[y]) |
| 25 | +return true; |
| 26 | +return false; |
| 27 | +} |
| 28 | +void dfs(TreeNode* root, int depth, unordered_map<int, int>& depths, unordered_map<int, int>& parents) |
| 29 | +{ |
| 30 | +if (root == nullptr) return; |
| 31 | +depths[root->val] = depth; |
| 32 | +if (root->left != nullptr) |
| 33 | +{ |
| 34 | +parents[root->left->val] = root->val; |
| 35 | +dfs(root->left, depth + 1, depths, parents); |
| 36 | +} |
| 37 | +if (root->right != nullptr) |
| 38 | +{ |
| 39 | +parents[root->right->val] = root->val; |
| 40 | +dfs(root->right, depth + 1, depths, parents); |
| 41 | +} |
| 42 | +return; |
| 43 | +} |
| 44 | +}; |
| 45 | + |
| 46 | +// Test |
| 47 | +int main() |
| 48 | +{ |
| 49 | +Solution sol; |
| 50 | +TreeNode* root = new TreeNode(1); |
| 51 | +root->left = new TreeNode(2); |
| 52 | +root->right = new TreeNode(3); |
| 53 | +root->left->right = new TreeNode(4); |
| 54 | +root->right->right = new TreeNode(5); |
| 55 | +auto res = sol.isCousins(root, 2, 3); |
| 56 | +cout << (res ? "True" : "False") << endl; |
| 57 | + |
| 58 | +return 0; |
| 59 | +} |
0 commit comments