Leetcode – Same Tree

Two binary trees are considered the same if they have identical structure and nodes have the same value.

This problem can be solved by using a simple recursive function.

public boolean isSameTree(TreeNode p, TreeNode q) {
    if(p==null && q==null){
        return true;
    }else if(p==null || q==null){
        return false;
    }
 
    if(p.val==q.val){
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }else{
        return false;
    }
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Dexter Morgan

    In two lines 🙂

    public boolean isSameTree(TreeNode p, TreeNode q) {
    if(p == null || q == null) return (p == q); // best part
    return isSameTree(p.left, q.left) && isSameTree(p.right, q.right) && p.val == q.val;
    }

  • Dexter Morgan

    what is the running time of this approach?

  • TIAN DU

    the last return statement is unreachable, i think