Skip to content

Instantly share code, notes, and snippets.

@daifu
Created April 28, 2013 06:32
Show Gist options
  • Save daifu/5476106 to your computer and use it in GitHub Desktop.
Save daifu/5476106 to your computer and use it in GitHub Desktop.
Same Tree
/*
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
Algorithm:
1. It is a recursive function that check p.left and q.left,
and p.right and p.right, and p.val and q.val
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
// Start typing your Java solution below
// DO NOT write main() function
if(p == null && q == null) return true;
if(p == null) return false;
if(q == null) return false;
if(p.val != q.val) return false;
boolean left = isSameTree(p.left, q.left);
boolean right = isSameTree(p.right, q.right);
return left && right && (p.val == q.val);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment