题目:
100. 相同的树
题解:
代码:
public class code100 {
public static boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
if (p.val != q.val) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
public static void main(String[] args) {
Integer nums1[] = { 1, 2 };
Integer nums2[] = { 1, null, 2 };
System.out.println("***************************************");
TreeNode tree1 = ConstructTree.constructTree(nums1);
TreeOperation.show(tree1);
System.out.println("***************************************");
TreeNode tree2 = ConstructTree.constructTree(nums2);
TreeOperation.show(tree2);
System.out.println("***************************************");
boolean flag = isSameTree(tree1, tree2);
System.out.println(flag);
}
}
参考:
- 相同的树
- 画解算法:100. 相同的树
- 写树算法的套路框架