Skip to content

Instantly share code, notes, and snippets.

@fpdjsns
Created February 17, 2019 10:45
Show Gist options
  • Save fpdjsns/84b7c2386c834050750401c85011599d to your computer and use it in GitHub Desktop.
Save fpdjsns/84b7c2386c834050750401c85011599d to your computer and use it in GitHub Desktop.
[leetcode][993] Cousins in Binary Tree : https://leetcode.com/problems/cousins-in-binary-tree/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
pair<int,int> parentAndDepth_x = {-1,-1};
pair<int,int> parentAndDepth_y = {-1,-1};
int X = 0;
int Y = 0;
void setParentAndDepth(TreeNode* root, int parent, int depth){
if(root == NULL) return;
int val = root->val;
if(val == X)
parentAndDepth_x = {parent, depth};
if(val == Y)
parentAndDepth_y = {parent, depth};
setParentAndDepth(root->left, val, depth+1);
setParentAndDepth(root->right, val, depth+1);
}
public:
bool isCousins(TreeNode* root, int x, int y) {
X = x;
Y = y;
setParentAndDepth(root, -1, 0);
return (parentAndDepth_x.first != parentAndDepth_y.first &&
parentAndDepth_x.second == parentAndDepth_y.second);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment