Same Tree
Total Accepted: 132356
Total Submissions: 304237
Difficulty: Easy
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
Subscribe to see which companies asked this question
c++ code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
bool isSam;
/*
void preOrder(TreeNode* p, TreeNode* q)
{
if(!isSam) return;
if(NULL == p && NULL == q) return;
if(NULL == p && NULL!= q || NULL != p && NULL== q)
{
isSam = false;
return;
}
if(p->val != q->val)
{
isSam = false;
return;
}
preOrder(p->left, q->left);
preOrder(p->right, q->right);
}
*/
void inOrder(TreeNode* p, TreeNode* q)
{
if(!isSam) return;
if(NULL == p && NULL == q) return;
if(NULL == p && NULL!= q || NULL != p && NULL== q)
{
isSam = false;
return;
}
inOrder(p->left, q->left);
if(p->val != q->val)
{
isSam = false;
return;
}
inOrder(p->right, q->right);
}
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
isSam = true;
//preOrder(p,q);
inOrder(p,q);
return isSam;
}
};