题目:

100. 相同的树

题解:

代码:

/** * code100 */
public class code100 {

    public static boolean isSameTree(TreeNode p, TreeNode q) {
        // p and q are both null
        if (p == null && q == null) {
            return true;
        }
        // one of p and q is null
        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);
    }
}

参考:

  1. 相同的树
  2. 画解算法:100. 相同的树
  3. 写树算法的套路框架