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.
Recursive Solution
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) { // 时间复杂度O(n),平均空间复杂度O(sqrt(n)),BinarySearch Tree空间复杂度为O(lgn)
if(p==NULL&&q==NULL)
return true;
if(p==NULL&&q!=NULL||p!=NULL&&q==NULL)
return false;
if(p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right))
return true;
else
return false;
}
};
iterative Solution
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
// 时间复杂度为O(n),平均空间复杂度为O(sqrt(n))
stack<TreeNode*> treeStack;
treeStack.push(p);
treeStack.push(q);
while(!treeStack.empty()&&!treeStack.empty())
{
p=treeStack.top();
treeStack.pop();
q=treeStack.top();
treeStack.pop();
if(p==NULL&&q==NULL)
continue;
if(p&&q&&p->val==q->val)
{
treeStack.push(p->left);
treeStack.push(q->left);
treeStack.push(p->right);
treeStack.push(q->right);
}
else
return false;
}
}
};