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.

Subscribe to see which companies asked this question.

這個問題首先思考如果兩個樹都是NULL,那麼就return true,接下來如果有一顆是NULL另外一顆不是NULL,那麼就返回false,這可以用一個if語句來表示。

    if(p==NULL || q==NULL)
    return p==q;

接下來來思考只有一個node的樹,如果p和q都沒有左右樹,而且val一樣,那麼就返回true。

    if(p->left==NULL && p->right==NULL && q->left==NULL && q->right==NULL && p->val==q->val)
    return true;
然後如果兩個val不一樣,就返回false。

    if(p->val!=q->val)
    return false;

最後一種情況是q和p都有左子樹或者右子樹,那麼就比較左子樹和右子樹是否相同,進入遞歸。

else 
    return (isSameTree(p->left,q->left))&&(isSameTree(p->right,q->right));

總的程序是:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
 
    if(p==NULL || q==NULL)
    return p==q;
    if(p->left==NULL && p->right==NULL && q->left==NULL && q->right==NULL && p->val==q->val)
    return true;
    if(p->val!=q->val)
    return false;
    else 
    return (isSameTree(p->left,q->left))&&(isSameTree(p->right,q->right));
}

其實判斷只有一個node的樹是多餘的步驟,因爲如果刪除那個判斷步驟,兩課樹val一樣的話,那麼會判斷兩顆樹的左子樹和右子樹,都是NULL,所以返還true。下面程序和上面程序一樣的效果。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
 
    if(p==NULL || q==NULL)
    return p==q;
    if(p->val!=q->val)
    return false;
    else 
    return (isSameTree(p->left,q->left))&&(isSameTree(p->right,q->right));
}


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