|
| 1 | +/* |
| 2 | +In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1. |
| 3 | + |
| 4 | +Two nodes of a binary tree are cousins if they have the same depth, but have different parents. |
| 5 | + |
| 6 | +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. |
| 7 | + |
| 8 | +Return true if and only if the nodes corresponding to the values x and y are cousins. |
| 9 | + |
| 10 | +Example: |
| 11 | + |
| 12 | + 6 |
| 13 | + / \ |
| 14 | + 3 5 |
| 15 | + / \ / \ |
| 16 | +7 8 1 3 |
| 17 | + |
| 18 | +Say two node be 7 and 1, result is TRUE. |
| 19 | +Say two nodes are 3 and 5, result is FALSE. |
| 20 | +Say two nodes are 7 and 5, result is FALSE. |
| 21 | +*/ |
| 22 | + |
| 23 | + |
| 24 | +/** |
| 25 | + * Definition for a binary tree node. |
| 26 | + * public class TreeNode { |
| 27 | + * int val; |
| 28 | + * TreeNode left; |
| 29 | + * TreeNode right; |
| 30 | + * TreeNode(int x) { val = x; } |
| 31 | + * } |
| 32 | + */ |
| 33 | + |
| 34 | +class Solution { |
| 35 | + public int x_level; |
| 36 | + public TreeNode x_parent; |
| 37 | + public int y_level; |
| 38 | + public TreeNode y_parent; |
| 39 | + |
| 40 | + public boolean isCousins(TreeNode root, int x, int y) { |
| 41 | + search(root, x, y, 0, null); |
| 42 | + |
| 43 | + return x_level == y_level && x_parent != y_parent; |
| 44 | + } |
| 45 | + |
| 46 | + public void search(TreeNode root, int x, int y, int level, TreeNode parent) |
| 47 | + { |
| 48 | + if(root== null) return ; |
| 49 | + if(root.val == x) |
| 50 | + { |
| 51 | + x_level = level; |
| 52 | + x_parent = parent; |
| 53 | + } |
| 54 | + if(root.val == y) |
| 55 | + { |
| 56 | + y_level = level; |
| 57 | + y_parent = parent; |
| 58 | + } |
| 59 | + search(root.left,x,y,level+1,root); |
| 60 | + search(root.right,x,y,level+1,root); |
| 61 | + } |
| 62 | +} |
0 commit comments