Skip to content

Instantly share code, notes, and snippets.

@iwilbert
Created July 22, 2014 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwilbert/96e4a0e45b2142f058e0 to your computer and use it in GitHub Desktop.
Save iwilbert/96e4a0e45b2142f058e0 to your computer and use it in GitHub Desktop.
public boolean isSubtree(TreeNode t1, TreeNode t2) {
if (t2 == null)
return true;
if (t1 == null)
return false;
if (isMatch(t1, t2))
return true;
return isSubtree(t1.left, t2) || isSubtree(t1.right, t2);
}
private boolean isMatch(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null)
return true;
if (t1 == null || t2 == null)
return false;
if (t1.val != t2.val)
return false;
return isMatch(t1.left, t2.left) && isMatch(t1.right, t2.right);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment