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
| private static class State { private int depth; private TreeNode parent; private boolean appeared; }
public boolean isCousins(TreeNode root, int x, int y) { State state = new State(); return dfs(state, null, 0, root, x, y); }
private boolean dfs(State state, TreeNode parent, int depth, TreeNode node, int x, int y) { if (node == null) { return false; }
if (node.val == x || node.val == y) { if (!state.appeared) { state.depth = depth; state.parent = parent; state.appeared = true; } else { return state.depth == depth && state.parent != parent; } }
return dfs(state, node, depth + 1, node.left, x, y) || dfs(state, node, depth + 1, node.right, x, y); }
|