LeetCode Solution: Same Tree

 Question: Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

Constraints:

  • The number of nodes in both trees is in the range [0, 100].
  • -10^4 <= Node.val <= 10^4
Solution: This solution first checks if both trees are empty, in which case they are the same. If only one of the trees is empty, they are not the same. If the values of the nodes are different, the trees are not the same. Otherwise, the function recursively checks the left and right subtrees.

class Solution {

    public boolean isSameTree(TreeNode p, TreeNode q) {
        // If both trees are empty, they are the same
        if (p == null && q == null) {
            return true;
        }
        // If only one tree is empty, they are not the same
        if (p == null || q == null) {
            return false;
        }
        // If the values of the nodes are different, the trees are not the same
        if (p.val != q.val) {
            return false;
        }
        // Check the left and right subtrees recursively
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

No comments:

Post a Comment