Question:
Given two binary trees, check whether they are identical or not.
Analyze:
we first compare the roots of these two trees, if they are the same, we continue to compare the root of their left and right subtrees.
Code:
boolean sameTree(Node a, Node b) {
// 1. both empty -> true
if (a == null && b == null) return(true);
// 2. both non-empty -> compare them
else if (a!=null && b!=null) {
return (a.data == b.data &&
sameTree(a.leftChild, b.leftChild) &&
sameTree(a.rightChild, b.rightChild)
);
}
// 3. one empty, one not -> false
else return false;
}
refenrence:
http://cslibrary.stanford.edu/110/BinaryTrees.html