题解 | #树的子结构#
树的子结构
http://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88
隔了几天在lc上看到又是不一样的思路,天天新题,愁得慌
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
TreeNode A = root1;
TreeNode B = root2;
if(B == null || A == null){
return false;
}
Queue<TreeNode> queue = new LinkedList<>();
Queue<TreeNode> queueB = new LinkedList<>();
Queue<TreeNode> queueA = new LinkedList<>();
TreeNode op;
TreeNode opA;
TreeNode opB = B;
queue.offer(A);
while(true){
op = queue.poll();
if(op.left != null ){
queue.offer(op.left);
}
if(op.right != null){
queue.offer(op.right);
}
opA = op;
queueA.offer(opA);
queueB.offer(B);
while(true){
opA = queueA.poll();
opB = queueB.poll();
if(opA.val != opB.val){
break;
}
if(opA.left == null && opB.left != null){
break;
}
if(opA.right == null && opB.right != null){
break;
}
if(opA.left != null && opB.left != null){
queueA.offer(opA.left);
queueB.offer(opB.left);
}
if(opA.right != null && opB.right != null){
queueA.offer(opA.right);
queueB.offer(opB.right);
}
if(queueA.isEmpty() && !queueB.isEmpty()){
return false;
}
else if(!queueA.isEmpty() && queueB.isEmpty()){
return true;
}
else if(queueA.isEmpty() && queueB.isEmpty()){
return true;
}
}
queueA.clear();
queueB.clear();
if(queue.isEmpty()){
break;
}
}
return false;
}
}