描述:
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.
方法:
就是簡(jiǎn)單的遞歸苟径,不知道我的代碼哪里出問(wèn)題了元咙,一直通不過(guò),看大神實(shí)現(xiàn)占调,發(fā)現(xiàn)了更簡(jiǎn)潔的寫法
C++代碼:
/**
* 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) {
if(p == NULL || q == NULL)
return p == q;
if(q->val != p->val)
return false;
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};