題目:
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.
題意:
給兩個二叉樹,要求實現判斷這兩棵樹是否相同。
假如兩棵樹相同,那麼對於樹上對應的每一個節點,都應該相同,採用中序遍歷的辦法,一邊判斷,一邊遍歷。
代碼如下:
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if ((!p&&q) || (p&&!q)) return false;
if (!q && !p) return true;
if (p->val != q->val) return false;
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right) && p->val == q->val;
}
};