Skip to content

Commit

Permalink
Create cousinsInBinaryTree.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
anishmo99 committed Oct 8, 2020
1 parent 83c6afd commit 219cf82
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions DFS/cousinsInBinaryTree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* 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
{
vector<pair<TreeNode *, int>> res;

public:
void dfs(TreeNode *node, TreeNode *root, int depth, int x, int y)
{
if (!node)
return;

if (node->val == x)
{
res.emplace_back(root, depth);
}

if (node->val == y)
{
res.emplace_back(root, depth);
}

dfs(node->left, node, depth + 1, x, y);
dfs(node->right, node, depth + 1, x, y);
}
bool isCousins(TreeNode *root, int x, int y)
{
dfs(root, nullptr, 0, x, y);

auto node_x = res[0];
auto node_y = res[1];

return node_x.first != node_y.first and node_x.second == node_y.second;
}
};

0 comments on commit 219cf82

Please sign in to comment.