LeetCode No.100 Same Tree | #Tree

Q:

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.

A:

/**
 * 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 false;
       return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); //迭代! 
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • “什么垃圾,也來這里發(fā)表文章” 可能是吧,文筆差,看的書也不多,也不是某某中文畢業(yè)的,確實沒什么資格給大家分享 但...
    7e1529120fd8閱讀 605評論 0 0
  • 碎戲臺詞說:我家后院養(yǎng)了一條狗一只羊 狗覺得羊啃不了骨頭就不幸福 羊覺得狗吃不了青草就不幸福 我說:你是大都市櫥窗...
    馬桶左便器閱讀 135評論 0 0
  • 加入圈子,寫寫寫! 沒加入小灶群時,想都沒想過自己有“寫作”的能力。 因為從大腦中按思路來碼出字,對從不看書的我來...
    靈魂獸者閱讀 222評論 1 4
  • 我曾無數(shù)次路過你在每一個消亡了星星的黑夜里你抿嘴的樣子你時而高亢時而低沉的表情你模糊而漸遠的身影都那么的清晰 我不...
    勞心者閱讀 413評論 19 0

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