地址:http://oj.leetcode.com/problems/same-tree/
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.
思路:用递归的思路。如果p和q都为空,返回true。若p和q都非空,1. 比较p->val 和 q->val
2. 然后,递归调用 p->left 和 q->left
3. 最后,递归调用 p->right 和 q->right
只有走完三步才返回true,否则返回false
参考代码:
updated SECOND TRIAL, 4ms
/**
* 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)
return !q;
else if(!q)
return false;
return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};