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.

大意:

給出兩個二叉樹,寫一個函數來檢查兩者是否相等。
所謂相等,是指他們結構相同且節點有同樣的值。

思路:

這個思路還比較直接,考慮全面一點就好了。首先考慮節點為空的情況,如果兩個都為空,那么直接相等;如果一個為空一個不為空,那么不相等;如果兩個都不為空,那么繼續進行深層次的判斷。
首先看兩個節點的值是否相等,不相等則二叉樹不等,然后判斷其子節點,這時候使用遞歸就可以了,對兩個節點的左節點和右節點分別調用這個函數,只有都返回相等時,才表示兩個節點完全相同,由于遞歸,其子節點也就一層層地判斷下去了,整個二叉樹就會遍歷完成。

代碼(Java):

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (p != null && q != null) {
            if (p.val != q.val) return false;
        
            if (isSameTree(p.left, q.left) && isSameTree(p.right, q.right)) return true;
            else return false;
        } else {
            return false;
        }
    }
}

其實還可以進一步精簡代碼,可以看下Discuss最火的代碼,思路是一致的,只是精簡到了極致,確實很贊:

精簡代碼(Java):

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null) return true;
        if(p == null || q == null) return false;
        if(p.val == q.val)
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        return false;
    }
}

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容