AlgoMaster Logo

Same Tree

tree1=[1, 2, 3],tree2=[1, 2, 3]
1class Solution {
2    public boolean isSameTree(TreeNode p, TreeNode q) {
3        // If both nodes are null, the subtrees are identical
4        if (p == null && q == null) {
5            return true;
6        }
7
8        // If one is null and the other is not, not identical
9        if (p == null || q == null) {
10            return false;
11        }
12
13        // If the values differ, not identical
14        if (p.val != q.val) {
15            return false;
16        }
17
18        // Recursively check left and right subtrees
19        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
20    }
21}
0 / 14
Tree p123Tree q123