Posts Same Tree
Post
Cancel

Same Tree

PROBLEM DESCRIPTION

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.

Leetcode

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {

        //if p and q both are null, return true
        if(p == null && q == null) return true;

        //if either p or q is null, return false (if both were null, they would have not reached here)
        if(p == null || q == null) return false;
        
        //if the values of p and q are not same, return false
        if(p.val != q.val) return false;

        //at this point, the current nodes are same
        //we need to do the same recursively for LST of p and q & RST of p and q
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);

    }
}
This post is licensed under CC BY 4.0 by the author.