100 Same Tree


title: Same Tree
tags:
- same-tree
- No.100
- simple
- tree
- recurrence
- depth-first-search


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

Corner Cases

  • two empty trees
  • one empty tree
  • null node

Solutions

Pre-Order Depth First Search

Take depth first search to compare sub-trees. Use pre-order because we can stop the program as soon as an inequal case is detected.

For any tree node, if the height of the left sub-tree is h_L and the height of the right one is h_R, then we have:

T(\max\{h_L, h_R\} + 1) = T(h_L) + T(h_R) + O(1)

Since we visit each edge and vertex once, then running time is O(V + E).

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

Stack Without Recurrence

Use stack to implement pre-order DFS and compare the two trees.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        Stack<TreeNode> sp = new Stack<TreeNode>();
        Stack<TreeNode> sq = new Stack<TreeNode>();

        TreeNode xp = p;
        TreeNode xq = q;

        if (p == null && q != null) {return false;}

        while (xp != null || !sp.empty()) {
            if (xp != null) {
                if (xq == null)       {return false;}
                if (xp.val != xq.val) {return false;}
                sp.push(xp);
                sq.push(xq);
                xp = xp.left;
                xq = xq.left;
            } else { //xp == null && !sp.empty()
                if (xq != null) {return false;}
                TreeNode tp = sp.pop();
                TreeNode tq = sq.pop();
                xp = tp.right;
                xq = tq.right;
            }
        }
        return true;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,424評(píng)論 0 10
  • 爸爸出差了。 從計(jì)劃到出行足足有兩個(gè)月。 這兩個(gè)月里,媽媽一直都處于焦慮的狀態(tài),吃不好睡不好,擔(dān)心爸爸走了之后咱們...
    江小馨閱讀 314評(píng)論 3 3
  • 時(shí)間7.7號(hào) 車(chē)架號(hào)0450623 045076 時(shí)間7.12 車(chē)架號(hào)050651 時(shí)間7.12 車(chē)架號(hào)05028...
    丿肆悅閱讀 202評(píng)論 0 0
  • 最近又陷入了日常喪。 回來(lái)的前一天喉嚨被鴨脆骨卡了喉嚨,嘔吐了好久,但嗓子里依然有種怪怪的感覺(jué),不是卡,但感覺(jué)有什...
    樹(shù)風(fēng)水閱讀 359評(píng)論 0 0
  • 遇到一個(gè)同事,一直感慨自己的孩子日記寫(xiě)不來(lái),不知道該寫(xiě)些什么,她說(shuō),火來(lái)就讓這孩子每天都寫(xiě)一篇日記,隨便她寫(xiě)什么,...
    一塵720閱讀 139評(píng)論 4 2