我的代码 很冗余
/**
* 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;
}
if(p==null && q!=null){
return false;
}
Queue<TreeNode> quetree1 = new LinkedList<>();
Queue<TreeNode> quetree2 = new LinkedList<>();
quetree1.offer(p);
quetree2.offer(q);
while(!quetree1.isEmpty() && !quetree2.isEmpty()){
TreeNode tree1 = quetree1.poll();
TreeNode tree2 = quetree2.poll();
if(tree1.val != tree2.val){
return false;
}
if(tree1.left == null && tree2.left!=null){
return false;
}
if(tree1.left != null && tree2.left==null){
return false;
}
if(tree1.right == null && tree2.right!=null){
return false;
}
if(tree1.right !=null && tree2.right ==null){
return false;
}
if(tree1.left!=null && tree2.left!=null){
quetree1.offer(tree1.left);
quetree2.offer(tree2.left);
}
if(tree1.right!= null && tree2.right!=null){
quetree1.offer(tree1.right);
quetree2.offer(tree2.right);
}
}
return quetree1.isEmpty()&&quetree2.isEmpty();
}
}
答案代码
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
} else if (p == null || q == null) {
return false;
}
Queue<TreeNode> queue1 = new LinkedList<TreeNode>();
Queue<TreeNode> queue2 = new LinkedList<TreeNode>();
queue1.offer(p);
queue2.offer(q);
while (!queue1.isEmpty() && !queue2.isEmpty()) {
TreeNode node1 = queue1.poll();
TreeNode node2 = queue2.poll();
if (node1.val != node2.val) {
return false;
}
TreeNode left1 = node1.left, right1 = node1.right, left2 = node2.left, right2 = node2.right;
if (left1 == null ^ left2 == null) {
return false;
}
if (right1 == null ^ right2 == null) {
return false;
}
if (left1 != null) {
queue1.offer(left1);
}
if (right1 != null) {
queue1.offer(right1);
}
if (left2 != null) {
queue2.offer(left2);
}
if (right2 != null) {
queue2.offer(right2);
}
}
return queue1.isEmpty() && queue2.isEmpty();
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/same-tree/solution/xiang-tong-de-shu-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
^为异或。