Given the roots of two binary trees
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
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.
Input: p = [1,2,3], q = [1,2,3]
Output: trueApproach
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 treestatic boolean isSameTree(TreeNode p, TreeNode 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.left, q.left) && isSameTree(p.right, q.right);}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data=data;this->left=NULL;this->right=NULL;}};//function to check for same treebool isSameTree(TreeNode* p, TreeNode* 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";elsecout<<"false";return 0;}

No comments:
Post a Comment