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; } } |
This is brillant,
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;
}
what is the running time of this approach?
the last return statement is unreachable, i think