给定两个根结点分别为
和
二叉树,请判断这两棵树是否完全相同。
数据范围:
两棵树上的节点数目都在范围 [0, 100] 内
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root1 TreeNode类
* @param root2 TreeNode类
* @return bool布尔型
*/
public boolean isSameTree (TreeNode root1, TreeNode root2) {
// write code here
Queue<TreeNode> rootQueue1 = new LinkedList<>();
Queue<TreeNode> rootQueue2 = new LinkedList<>();
rootQueue1.offer(root1);
rootQueue2.offer(root2);
while (!rootQueue1.isEmpty() && !rootQueue2.isEmpty()) {
TreeNode poll1 = rootQueue1.poll();
TreeNode poll2 = rootQueue2.poll();
if(poll1 == null && poll2 == null) {
continue;
}
if (poll1 == null || poll2 == null || poll1.val != poll2.val) {
return false;
}
rootQueue1.offer(poll1.left);
rootQueue1.offer(poll1.right);
rootQueue2.offer(poll2.left);
rootQueue2.offer(poll2.right);
}
return true;
}
} public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root1 TreeNode类
* @param root2 TreeNode类
* @return bool布尔型
*/
public boolean isSameTree (TreeNode root1, TreeNode root2) {
if(root1 != null && root2 == null || root1 == null && root2 != null) return false;
if(root1 == null && root2 == null) return true;
if(root1.val != root2.val) return false;
return isSameTree(root1.left,root2.left) && isSameTree(root1.right,root2.right);
}
}