forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0993.cpp
More file actions
executable file
·29 lines (25 loc) · 793 Bytes
/
LC0993.cpp
File metadata and controls
executable file
·29 lines (25 loc) · 793 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/cousins-in-binary-tree
Time: O(n)
Space: O(h)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
bool isCousins(TreeNode* root, int x, int y) {
pair<TreeNode*, int> node_x, node_y;
node_x = search(root, x);
node_y = search(root, y);
return node_x.first != node_y.first && node_x.second == node_y.second;
}
pair<TreeNode*, int> search(TreeNode* node, int target, TreeNode* parent = nullptr, int depth = 0) {
if (!node)
return {nullptr, 0};
else if (node->val == target)
return {parent, depth};
pair<TreeNode*, int> left, right;
left = search(node->left, target, node, depth + 1);
right = search(node->right, target, node, depth + 1);
return (left.first) ? left : right;
}
};