LeetCode 100. 相同的树
给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/same-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
写了一个输出树的函数outputTree(),比较两颗树的输出,
/**
* Definition for a binary tree node.
* 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) {
if(p==NULL||q==NULL)
{
if(p==NULL&&q==NULL)
{
return true;
}
return false;
}
if(outputTree(p)==outputTree(q))return true;
return false;
}
string outputTree(TreeNode* p)
{
string a;
a=p->val+'0';
if(p->left==NULL) a+="NULL";
else a=a+outputTree(p->left);
if(p->right==NULL)a+="NULL";
else a=a+outputTree(p->right);
return a;
}
};
时间复杂度O(n+m)
空间复杂度O(n+m)