[LeetCode] 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.

Example 1:

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

Example 2:

Input: p = [1,2], q = [1,null,2]
Output: false

Example 3:

Input: p = [1,2,1], q = [1,1,2]
Output: false

Constraints:

  • The number of nodes in both trees is in the range [0, 100].
  • -104 <= Node.val <= 1049

这道题其实就是判断每一个树的root的值,以及它的左右子树是否相同,考虑用递归来做。所以最后返回的是判断值是否相同,左子树是否相同(递归调用),右子树是否相同(递归调用)。递归过程中,如果一个node不为null,一个为null,那么就是不相同。如果两个node都是null,那么就是相同。
注意的点:

  • 异或(^) 可以来判断两个情况是否相同。如果情况不同就是true,如果相同就是false。
    • true ^ true = false
    • false ^ false = false
    • true ^ false = true
    • false ^ true = true
    • 这道题里,如果q是null,p是不是null或者p是null,q不是null,那么异或后就是true,进入if条件,返回false,因为这就说明两棵树不相同。
  • 不要忘记了两个都是null的情况,不然进入递归,调用null的左右子树时就会报错。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null ^ q == null) {
            return false;
        }
        if (p == null && q == null) {
            return true;
        }
        return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

posted on 2021-12-29 09:55  codingEskimo  阅读(20)  评论(0编辑  收藏  举报

导航