【leetcode每日一题】100.same treet
题目:
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.
解析:
判断两棵二叉树,是否是相等的。对于两棵树相同位置的节点来说,如果两个节点都为NULL,则这两个节点时相等的;如果一个节点为NULL,另一个节点不为NULL,则这两个节点不等;如果两个节点都不为NULL,则判断两个节点指向的值是否相等。
代码如下:
/**
* 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) {
bool left,right;
if(p==NULL&&q==NULL)
return true;
else if(p!=NULL&&q!=NULL)
{
if(p->val!=q->val)
return false;
left=isSameTree(p->left,q->left);
right=isSameTree(p->right,q->right);
return left&&right;
}
else
return false;
}
};
还没有评论,来说两句吧...