100. Same Tree

Description:

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

My code:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */
var isSameTree = function(p, q) {
    if(p == null && q == null) {
        return true;
    } else if (p == null || q == null) {
        return false;
    } else if(p.val == q.val) { // 值相同時判斷左右子樹
       return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    } else {
       return false;
    }
};
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 21天日更結束后,逼著自己停更了幾天。除了這幾天工作比較忙之外,我也是想給自己一個思考的空間。日更挑戰結束后,所寫...
    墨莫末閱讀 286評論 6 2
  • 小時候,我無憂無慮,而現在我倚靠在窗臺,沐浴著陽光,內心卻是難受的。近幾天,回家信息如同無數根針一齊刺向我...
    馮海宇閱讀 256評論 0 0
  • 路燈癡癡的立著 空氣被黑暗擠干 白色的陽光逼迫瞳孔 北極星四處狂躥 獅子在逡巡風扯斷鬃毛 呼出白色的氣凝成鏡子 銀...
    風不值閱讀 263評論 0 3
  • 文|水湄 我收起鋒芒 我在寒夜里煮酒 我在下了霜的路口 等你 我卑微的像要低進泥土里 只為能夠靠近你 恨不得 傾盡...
    kathy湄閱讀 293評論 1 3
  • 概述 最近在學習Replugin源碼時,遇到了其中的多進程部分。由于太久沒使用,有點生疏,剛好重拾總結下。AIDL...
    PeytonWu閱讀 573評論 0 0