树的子结构
问题描述:判断二叉树B是不是二叉树A的子结构
首先考察基本功,先找到根节点一样的节点,然后递归的判断左子树和右子树,类似于前序遍历
本方法思想:先找到根节点一样的节点,然后递归的判断左子树和右子树,类似于前序遍历
持续更新...
代码附下
Java实现:
package 树的子结构;
//二叉树的数据结构
public class BinaryTree {
int val;
BinaryTree left = null;
BinaryTree right = null;
public BinaryTree(int val) {
this.val = val;
}
}
public class hasSubTree {
public static int count = 1;//计数用,记录遍历第几次找到子树结构
public static void main(String[] args) {//main方法构建一棵二叉树
/**
* A B 树 8 8 8 7 9 2 9 2 4 7
*/
BinaryTree rootA = new BinaryTree(8);
rootA.left = new BinaryTree(8);
rootA.right = new BinaryTree(7);
rootA.left.left = new BinaryTree(9);
rootA.left.right = new BinaryTree(2);
rootA.left.right.left = new BinaryTree(4);
rootA.left.right.right = new BinaryTree(7);
BinaryTree rootB = new BinaryTree(2);
rootB.left = new BinaryTree(4);
rootB.right = new BinaryTree(7);
System.out.println(hasSubTree(rootA, rootB));//测试用例
}
//B是否为A的子树
public static boolean hasSubTree(BinaryTree rootA, BinaryTree rootB) {
boolean result = false;
if (rootA != null && rootB != null) {
if (rootA.val == rootB.val) {//根相同时才有可能是子树
result = DoesTreeAHasTreeB(rootA, rootB);
if (result) {
System.out.println("这是第" + count + "次遍历,其中包括遍历了空节点");
}
}
if (!result) {//根不同,找左子树
count++;
result = hasSubTree(rootA.left, rootB);
}
if (!result) {//左子树不相同找右子树
count++;
result = hasSubTree(rootA.right, rootB);
}
}
return result;
}
//如果根相同,判断B是否为A的子树
private static boolean DoesTreeAHasTreeB(BinaryTree rootA, BinaryTree rootB) {
if (rootB == null) {//B没有时就是相同了
return true;
}
if (rootA == null) {
return false;
}
if (rootA.val != rootB.val) {//值不相等肯定不是子树
return false;
}
return DoesTreeAHasTreeB(rootA.left, rootB.left) && DoesTreeAHasTreeB(rootA.right, rootB.right);//递归判断左右子树
}
}
持续更新...欢迎赞赏!![](https://i-blog.csdnimg.cn/blog_migrate/ca0cc5c488ad24501c0bbddad6302b17.png)
主页:https://blog.csdn.net/ustcer_93lk/article/details/80374008
如果有问题,欢迎大家留言,有更好的方法也期待大家告知。