Untitled

 avatar
unknown
plain_text
a month ago
2.7 kB
2
Indexable
class Solution {
    private TreeNode parentX = null, parentY = null;
    private int depthX = -1, depthY = -1;

    public boolean isCousins(TreeNode root, int x, int y) {
        findDepthAndParent(root, null, 0, x, y);
        // Check if x and y are at the same depth but have different parents
        return depthX == depthY && parentX != parentY;
    }

    private void findDepthAndParent(TreeNode node, TreeNode parent, int depth, int x, int y) {
        if (node == null) return;

        // Recursively traverse the left and right subtrees
        findDepthAndParent(node.left, node, depth + 1, x, y);
        findDepthAndParent(node.right, node, depth + 1, x, y);

        // Process the current node after its children
        if (node.val == x) {
            parentX = parent;
            depthX = depth;
        } else if (node.val == y) {
            parentY = parent;
            depthY = depth;
        }
    }
}


import java.util.*;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public boolean isCousins(TreeNode root, int x, int y) {
        if (root == null) return false;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            boolean foundX = false, foundY = false;

            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();

                // Check if current node's children are x and y
                if (node.left != null && node.right != null) {
                    if ((node.left.val == x && node.right.val == y) ||
                        (node.left.val == y && node.right.val == x)) {
                        return false; // Same parent
                    }
                }

                // Check if the current node is either x or y
                if (node.val == x) foundX = true;
                if (node.val == y) foundY = true;

                // Add children to the queue
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }

            // If both nodes are found at the same level but different parents
            if (foundX && foundY) return true;

            // If one is found but not the other
            if (foundX || foundY) return false;
        }

        return false; // x and y are not cousins
    }
}
Leave a Comment