0100. Same Tree

100. Same Tree #

题目 #

给定两棵二叉树的根节点 pq,判断这两棵树是否相同。

若两棵树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

思路 #

代码 #

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) return q == null;
        if (q == null) return false;
        
        return (p.val == q.val) & isSameTree(p.left, q.left) & isSameTree(p.right, q.right);
    }
}