1、前言
题目描述2、思路
这道题的思路可以拿对称二叉树的解法来做,只不过相同的树比较的是 left.left 跟 right.left,和 left.right 跟 right.right。
3、代码
/**
* 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 true;
}
if(p == null || q == null){
return false;
}
return p.val == q.val && isSameTree(p.left, q.left)
&& isSameTree(p.right, q.right);
}
}
网友评论