LeetCode 100 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.

題目鏈接

題意:

給兩個二叉樹,要求實現判斷這兩棵樹是否相同。

假如兩棵樹相同,那麼對於樹上對應的每一個節點,都應該相同,採用中序遍歷的辦法,一邊判斷,一邊遍歷。

代碼如下:

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;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章