思路
典型的递归解法,注意递归的结束条件
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
//同时为空
if(p == null && q == null)
return true;
//p、q中有一个为空,一个不为空(
if(p == null || q == null)
return false;
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
网友评论