← Trees

Same Tree

Easy
Python
def is_same_tree(p,q):
    if not p and not q: return True
    if not p or not q: return False
    return p.val==q.val and is_same_tree(p.left,q.left) and is_same_tree(p.right,q.right)
Java
public boolean isSameTree(TreeNode p,TreeNode q){
    if(p==null&&q==null) return true;
    if(p==null||q==null) return false;
    return p.val==q.val&&isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}

Key Insight

Python truthiness vs Java null checks. 'and' vs '&&'.

Python → Java Differences

  • 'not p and not q' vs explicit null
  • 'and' vs '&&'
  • Recursive comparison identical
Python
def is_same_tree(p,q):
    if not p and not q: return True
    if not p or not q: return False
    return p.val==q.val and is_same_tree(p.left,q.left) and is_same_tree(p.right,q.right)
Java
public boolean isSameTree(TreeNode p,TreeNode q){
    if(p==null&&q==null) return true;
    if(p==null||q==null) return false;
    return p.val==q.val&&isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}

Algorithm Steps

1. Both null: true
2. One null: false
3. Compare and recurse