題目

  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.

想法

  一開始想到用前序和中序相同的,表示結構相同,但後來實驗結果,似乎少考慮了一些部分,回歸的最初的遞迴

首先可能節點是空的,那就回傳 true;

第二如果一方為空、一方不為空,那即是 false;

第三如果兩邊都不為空,就檢查節點的值,不同就回傳 false;相同就遞迴下去,檢查她的左右子樹。

code

bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
    if(p==0&&q==0)
        return true;
    else if(p==0&&q!=0 || p!=0&&q==0)
        return false;
    else if(p!=0&&q!=0){
        if(p->val==q->val)
            return (isSameTree(p->left, q->left)&&isSameTree(p->right, q->right));
        else
            return false;
    }
    return;
    
}

 

arrow
arrow
    文章標籤
    LeetCode C
    全站熱搜

    Davis 發表在 痞客邦 留言(0) 人氣()