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;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        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:
String foo = "bar";

  1. TIAN DU on 2014-12-26

    the last return statement is unreachable, i think

  2. Dexter Morgan on 2015-11-22

    what is the running time of this approach?

  3. Dexter Morgan on 2015-11-22

    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;

Leave a comment