100. Same Tree[Easy]

100. Same Tree

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

Constraints:
The number of nodes in both trees is in the range [0, 100].
-10^4 <= Node.val <= 10^4

Example
image

Input: p = [1,2,3], q = [1,2,3]
Output: true

思路

递归遍历二叉树

题解

    public boolean isSameTree(TreeNode p, TreeNode q) {
       if (p == null && q == null)
            return true;
        //  上面判断两个都为null的情况已经返回了,所以下面只有有一个为null,另一个肯定不是null
        if ((p == null || q == null) || (p.val != q.val))
            return false;

        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
posted @ 2023-02-06 16:22  AaronTanooo  阅读(20)  评论(0)    收藏  举报