LeetCode題目之100-Same Tree

題目描述如下:

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input:     1           1
              / \         / \
            2   3     2   3

        [1,2,3],   [1,2,3]

Output: true
Example 2:

Input:     1         1
             /             \
           2               2

        [1,2],     [1,null,2]

Output: false
Example 3:

Input:     1          1
              / \         / \
            2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

 

個人思路:

       該題目肯定是需要用到二叉樹的遍歷相關知識。當然,最簡單的就是層序遍歷了。本題目只需要對層序遍歷算法稍加修改即可。在實現層序遍歷的時候,我們一般藉助隊列來完成。

       首先是根節點入隊,然後開始循環遍歷,取出隊頭元素,判斷兩個樹的該節點的值val是否相等,如果不等直接返回false。如果相等的話則把該結點出隊。

       然後判斷兩棵樹的該結點是否還有左子樹,如果都有的話則左子樹節點入隊;如果是一個有一個沒有,則兩顆二叉樹在結構上已經相異,此時返回false;如果都沒有左子樹,則轉去判斷右子樹。

       判斷右子樹的情況與左子樹相似,就不再贅述。

       判斷完成後即可進入下一輪循環,直到返回了false或者隊列爲空時循環結束並返回true。

代碼:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
bool isSameTree(TreeNode* p, TreeNode* q) {
        if(!p && !q) return true;  //處理特殊情況,兩棵樹皆空
        if(!p || !q) return false; //處理特殊情況,一個樹空一個非空
        
        queue<TreeNode*> p1;
        queue<TreeNode*> q1;
        p1.push(p);
        q1.push(q);
        while((!q1.empty()) && (!p1.empty())){ //層序遍歷循環
            TreeNode* tempP = p1.front();  //取隊頭
            TreeNode* tempQ = q1.front();  //取隊頭
            
            if(tempP->val != tempQ->val) { //判斷值相等
                return false;    
            }
            else{                          //當前判斷的結點出隊
                p1.pop();
                q1.pop();
            }
            
            if(tempP->left && tempQ->left){//判斷有無左子樹,兩個都有的話入隊
                p1.push(tempP->left);
                q1.push(tempQ->left);
            }
            else if(tempP->left != tempQ->left)return false; //兩個都沒有的話則依舊是結構相等,否則結構不相等返回false
            
            if(tempP->right && tempQ->right){//判斷有無右子樹,兩個都有的話入隊
                p1.push(tempP->right);
                q1.push(tempQ->right);
            }
            else if(tempP->right != tempQ->right)return false;//兩個都沒有的話則依舊是結構相等,否則結構不相等返回false
        }
        return true;
    }

 

發佈了9 篇原創文章 · 獲贊 0 · 訪問量 6938
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章