题目:
分析:
判断树是否相同,可以采用层次遍历,新建两个队列,把非空头结点放入,返回false的条件有3中,1一方有左右子树但另一方没有,2值不相同,3队列的size不同,即两个树的结点数不同
代码:
/**
* 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) {
Queue<TreeNode> queue1 = new LinkedList<TreeNode>();
Queue<TreeNode> queue2 = new LinkedList<TreeNode>();
if(p!=null){
queue1.offer(p);
}
if(q!=null){
queue2.offer(q);
}
while(queue1.size()!=0&&queue2.size()!=0){
TreeNode t1=queue1.poll();
TreeNode t2=queue2.poll();
if(t1.val!=t2.val||(t1.left!=null&&t2.left==null)||(t1.left==null&&t2.left!=null)||(t1.right!=null&&t2.right==null)||(t1.right==null&&t2.right!=null)){
return false;
}
if(t1.left!=null){
queue1.offer(t1.left);
queue2.offer(t2.left);
}
if(t1.right!=null){
queue1.offer(t1.right);
queue2.offer(t2.right);
}
}
if(queue1.size()==queue2.size()){
return true;
}else{
return false;
}
}
}