Cousins in Binary Tree
Last updated
Last updated
Input: root = [1,2,3,4], x = 4, y = 3
Output: falseInput: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: trueInput: root = [1,2,3,null,4], x = 2, y = 3
Output: false class Solution {
public boolean isCousins(TreeNode root, int x, int y) {
if (root == null) return false;
int[] info_x = helper(root, null, 0, x);
int[] info_y = helper(root, null, 0, y);
if (info_x == null || info_y == null) return false;
return info_x[0] == info_y[0] && info_x[1] != info_y[1];
}
// ret[0]: depth
// ret[1]: parent
private int[] helper(TreeNode root, TreeNode parent, int depth, int target) {
if (root == null) return null;
if (root.val == target) return new int[]{depth, parent == null ? Integer.MAX_VALUE : parent.val};
int[] left = helper(root.left, root, depth + 1, target);
if (left != null) return left;
int[] right = helper(root.right, root, depth + 1, target);
return right;
}
}