forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
67 lines (47 loc) · 1.35 KB
/
main.cpp
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/// Source : https://leetcode.com/problems/cousins-in-binary-tree/
/// Author : liuyubobobo
/// Time : 2019-02-16
#include <iostream>
#include <cassert>
using namespace std;
/// Two-Pass DFS
/// Time Complexity: O(n)
/// Space Complexity: O(h)
/// 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 {
public:
bool isCousins(TreeNode* root, int x, int y) {
if(!root || root->val == x || root->val == y)
return false;
pair<int, int> p1; // depth, parent
if(!dfs(root, x, 0, p1)) return false;
pair<int, int> p2;
if(!dfs(root, y, 0, p2)) return false;
return p1.first == p2.first && p1.second != p2.second;
}
private:
bool dfs(TreeNode* node, int x, int d, pair<int, int>& p){
if(node->left && node->left->val == x){
p = make_pair(d + 1, node->val);
return true;
}
if(node->right && node->right->val == x){
p = make_pair(d + 1, node->val);
return true;
}
if(node->left && dfs(node->left, x, d + 1, p))
return true;
if(node->right && dfs(node->right, x, d + 1, p))
return true;
return false;
}
};
int main() {
return 0;
}