Cousins in Binary Tree
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:
true
Note
Code
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:
true
Last updated
Input:
root =
[1,2,3,null,4]
, x = 2, y = 3
Output:
false/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Map<Integer, TreeNode> parent = new HashMap<>(); // key: val of node, val: parent node
Map<Integer, Integer> depth = new HashMap<>(); // key: val of node, val: depth
public boolean isCousins(TreeNode root, int x, int y) {
dfs(root, null);
return depth.get(x) == depth.get(y) && parent.get(x) != parent.get(y);
}
private void dfs(TreeNode root, TreeNode par) {
if (root == null) {
return;
}
parent.put(root.val, par);
depth.put(root.val, par == null ? 0 : 1 + depth.get(par.val));
dfs(root.left, root);
dfs(root.right, root);
}
}