100 Same Tree
Problem
Solution
This problem is a great example for recursion, two binary trees are same if and only if they have:
- same root node
- same left subtree
- same right subtree
To get the answer, just perform above check recursively for every trees and subtrees.
Code
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p != null && q != null) {
if (p.val == q.val) {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
if (p == null && q == null) {
return true;
}
return false;
}
}