100.Same Tree
题目链接https://leetcode.com/problems/same-tree/description/
题目大意:给出两棵二叉树,判断这两颗二叉树是否完全相同。
法一:利用层序遍历,两个队列分别遍历两颗树,将每个结点都放进队列中(无论是否为null),然后再依次进行判断,代码如下:
1 private static boolean isSameTree1(TreeNode p, TreeNode q) { 2 Queue<TreeNode> queueP = new LinkedList<TreeNode>(); 3 Queue<TreeNode> queueQ = new LinkedList<TreeNode>(); 4 queueP.offer(p); 5 queueQ.offer(q); 6 boolean flag = true; 7 while(!queueP.isEmpty() && !queueQ.isEmpty()) { 8 TreeNode nodeP = queueP.poll(); 9 TreeNode nodeQ = queueQ.poll(); 10 if((nodeP == null && nodeQ != null) || (nodeP != null && nodeQ == null)) { 11 return false; 12 } 13 else if(nodeP != null && nodeQ != null) { 14 if(nodeP.val != nodeQ.val) { 15 return false; 16 } 17 else { 18 queueP.offer(nodeP.left); 19 queueP.offer(nodeP.right); 20 queueQ.offer(nodeQ.left); 21 queueQ.offer(nodeQ.right); 22 } 23 } 24 } 25 if(!queueP.isEmpty() || !queueQ.isEmpty()) { 26 return false; 27 } 28 return flag; 29 }
法二:利用递归直接判断是否相同,若两个结点都为null,则返回true;若一个结点为null,则返回false;否则判断值是否相等,以及其左右子树是否相同,代码如下:
1 private static boolean isSameTree(TreeNode p, TreeNode q) { 2 if(p == null && q == null) { 3 return true; 4 } 5 if(p == null || q == null) { 6 return false; 7 } 8 else { 9 if(p.val != q.val) { 10 return false; 11 } 12 else { 13 return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 14 } 15 } 16 }