Same Tree

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


Approach

Java

public class SameTree {
    public static void main(String[] args) {
        TreeNode l1 = new TreeNode(1);
        l1.left = new TreeNode(2);
        l1.right = new TreeNode(3);

        TreeNode l2 = new TreeNode(1);
        l2.left = new TreeNode(2);
        l2.right = new TreeNode(3);
        System.out.println(isSameTree(l1, l2));
    }

    // function to check for same tree
    static boolean isSameTree(TreeNode pTreeNode q) {
        if (p == null && q == null)
            return true;
        if ((p == null && q != null) || (p != null && q == null))
            return false;
        if (p.val != q.val)
            return false;
        return isSameTree(p.leftq.left) && isSameTree(p.rightq.right);
    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int valTreeNode leftTreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;
//struct for treenode
struct TreeNode{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int data)
    {
        this->data=data;
        this->left=NULL;
        this->right=NULL;
    }
};

//function to check for same tree
bool isSameTree(TreeNode* pTreeNode* q
{
       if(p==NULL && q==NULL)
              return true;
       if((p==NULL &&q!=NULL)||(p!=NULL && q==NULL))
              return false;
       if(p->data!=q->data)
              return false;
        return isSameTree(p->left,q->left)
             &&isSameTree(p->right,q->right);
}

    
int main()
{

    TreeNode *root1=new TreeNode(1);
    root1->left=new TreeNode(2);
    root1->right=new TreeNode(3);

    
    TreeNode *root2=new TreeNode(1);
    root2->left=new TreeNode(2);
    root2->right=new TreeNode(3);

    if(isSameTree(root1,root2))
      cout<<"true";
    else
      cout<<"false";
    
     return 0;
    
}


No comments:

Post a Comment