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;
    }
}

4 thoughts on “Leetcode – Same Tree”

  1. 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