100. Same Tree

題目 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.

分析
判斷兩個二叉樹是否相等,只要每個都遍歷(前,中,后,層次)一下進(jìn)行對比即可.
籠統(tǒng)的我們也可以這樣認(rèn)為,只要兩個二叉樹的根節(jié)點(diǎn),左子樹右子樹都相等,那么這兩個二叉樹就相等
1,遞歸
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    //比較倆二叉樹相等,只需根節(jié)點(diǎn),左子樹和右子樹三者都相等.否則,就是不相等
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //1,邊界條件判斷
        if(p == null && q == null){
            return true;
        }
        
        if(p == null || q == null){
            return false;
        }
        
        //2,比較根節(jié)點(diǎn)
        if(p.val == q.val){
            //3,比較左右子樹
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        }
        return false;
    }
}
時間復(fù)雜度O(n),空間復(fù)雜度O(1)
2,簡潔的代碼
/**
 * 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 p == q;
        }  
        return (p.val == q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}
時間復(fù)雜度O(n),空間復(fù)雜度O(1)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 常見的變量有哪些? 在C語言中常見的變量如下: 自動變量(Auto),也可以稱為局部變量 函數(shù)參數(shù)(形參) 靜態(tài)變...
    涼白開0072閱讀 304評論 0 0
  • 本文參與#漫步青春#征文活動,作者楊亞濤,本人承諾,文章內(nèi)容為原創(chuàng),且未在其他平臺發(fā)布 ...
    楊亞濤123閱讀 265評論 0 0
  • 現(xiàn)在下班回家天都黑了,小寶貝居然還來接我了。一看到我就撒嬌讓我抱,一路上問個不停,這是什么,是做什么的,一個...
    霞光暖陽閱讀 109評論 0 0

友情鏈接更多精彩內(nèi)容