如果弄清楚了子树,那么相同的树比子树的情况要简单,碰到不相等可以直接返回。
/**
* 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) {
return isSame(p,q);
}
private boolean isSame(TreeNode p, TreeNode q)
{
if(p==null||q==null)
{
if(p==null&&q==null)
return true;
else
return false;
}
if(p.val==q.val)
return isSame(p.left,q.left)&&isSame(p.right,q.right);
else
return false;
}
}
网友评论