思路
1.首先判断主树和从树都不能为空
2. 对主树的每一个节点进行遍历
3. 每遍历一个节点判断他和从树根节点的值一不一样,一样则有可能为子树
- 一样则判断该节点的左节点是否等于从树的左节点,右节点是否等于从树的右节点,直到
(一)从树的节点为空
说明
1.以主树当前节点为根的结点的树和从树都走到了叶子结点
2.从树走到了叶子结点
返回true。
(二)以主树当前节点为根结点 的树 的子节点 为空 且 从树对应的子节点不为空 说明 从树不是 以主树当前节点为根结点 的树 的子树。
- 一样且子树不为空就说明它是子树,否则继续遍历
代码
import java.util.LinkedList;
import java.util.Queue;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public boolean HasSubtree(TreeNode root1, TreeNode root2) {
if(root2 == null || root1 == null) {//两棵树都不能为空
return false;
}
//层序遍历二叉树
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root1);
TreeNode temp = null;
while(!queue.isEmpty()) {
temp = queue.poll();
if(temp.val == root2.val) {//判断该节点和从树根节点的值一不一样
boolean tag = isSubtree(temp, root2);
if(tag) {
return true;
}
}
if(temp.left != null) {
queue.add(temp.left);
}
if(temp.right != null) {
queue.add(temp.right);
}
}
return false;
}
public boolean isSubtree(TreeNode root1,TreeNode root2) {
if(root2 == null)return true;//1.以主树当前节点为根的结点的树和从树都走到了叶子结点
// 2.从树走到了叶子结点
if(root1 == null || root2 == null)return false; // 从树不是 以主树当前节点为根结点 的树 的子树。
if(root1.val == root2.val) {
return isSubtree(root1.left, root2.left)&&isSubtree(root1.right, root2.right);
}
return false;
}
}