Same Tree LeetCode Solution

Here, We see Same Tree LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Same Tree LeetCode Solution

Same Tree LeetCode Solution

Problem Statement

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.

Example 1:

Input: p = [1,2,3], q = [1,2,3]
Output: true

Example 2:

Input: p = [1,2], q = [1,null,2]
Output: false

Example 3:

Input: p = [1,2,1], q = [1,1,2]
Output: false

Same Tree Leetcode Solution C++

class Solution {
    bool isSameTree(TreeNode* p, TreeNode* q) {
          queue<TreeNode *> queue;
          while (queue.size()!=0){
              TreeNode * q2=queue.front();
              TreeNode * q1=queue.front();
              if (q1==nullptr && q2==nullptr) continue;
              if (q1==nullptr || q2==nullptr) return false;
              if (q1->val!=q2->val) return false;
          return true;        
};Code language: PHP (php)

Same Tree Leetcode Solution Java

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true;
        return p != null && q != null && p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);        
}Code language: PHP (php)

Same Tree Leetcode Solution JavaScript

var isSameTree = function(p, q) {
    return JSON.stringify(p)===JSON.stringify(q)    
};Code language: JavaScript (javascript)

Same Tree Leetcode Solution Python

class Solution(object):
    def isSameTree(self, p, q):
        if p==None and q==None:
            return True
        elif p==None or q==None:
            return False
        if p.val==q.val:
            return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
            return False
Scroll to Top