-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLC993.cpp
More file actions
47 lines (38 loc) · 1.09 KB
/
Copy pathLC993.cpp
File metadata and controls
47 lines (38 loc) · 1.09 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
class Solution {
public:
bool isCousins(TreeNode* root, int x, int y) {
if (!root)
return false;
TreeNode* xParent = nullptr;
TreeNode* yParent = nullptr;
int xDepth = -1;
int yDepth = -1;
struct NodeInfo {
TreeNode* node;
TreeNode* parent;
int depth;
};
stack<NodeInfo> st;
st.push({root, nullptr, 0});
while (!st.empty()) {
auto [node, parent, depth] = st.top();
st.pop();
if (node->val == x) {
xParent = parent;
xDepth = depth;
}
else if (node->val == y) {
yParent = parent;
yDepth = depth;
}
// Optional early exit
if (xDepth != -1 && yDepth != -1)
break;
if (node->right)
st.push({node->right, node, depth + 1});
if (node->left)
st.push({node->left, node, depth + 1});
}
return xDepth == yDepth && xParent != yParent;
}
};