-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path993. Cousins in Binary Tree
62 lines (50 loc) · 1.48 KB
/
993. Cousins in Binary Tree
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
/*
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
Return true if and only if the nodes corresponding to the values x and y are cousins.
Example:
6
/ \
3 5
/ \ / \
7 8 1 3
Say two node be 7 and 1, result is TRUE.
Say two nodes are 3 and 5, result is FALSE.
Say two nodes are 7 and 5, result is FALSE.
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int x_level;
public TreeNode x_parent;
public int y_level;
public TreeNode y_parent;
public boolean isCousins(TreeNode root, int x, int y) {
search(root, x, y, 0, null);
return x_level == y_level && x_parent != y_parent;
}
public void search(TreeNode root, int x, int y, int level, TreeNode parent)
{
if(root== null) return ;
if(root.val == x)
{
x_level = level;
x_parent = parent;
}
if(root.val == y)
{
y_level = level;
y_parent = parent;
}
search(root.left,x,y,level+1,root);
search(root.right,x,y,level+1,root);
}
}