题目:
输入两棵二叉树A和B,判断B是不是A的子结构,比如下图,左边是A树,右边是B树。
分析:
第一步,在树A中找到和树B的根节点的值应用的结点R。
这一步可以通过树的遍历来查找。可以采用递归或者循环的方式遍历。
第二步,判断树A中以R为根节点的子数是不是包含和树B应用的结构。
这里也采用递归的方式进行检测,递归的结束条件是A树或者B树到达了叶节点,在对比的过程中,如果A树达到了叶节点,但是B树还没有达到叶节点,此时A不是B的子树。如果B到达了叶节点,A到达或是没到达叶节点都可以,此时这条分支上是匹配的。
解法:
package com.wsy;
class Tree {
private int value;
private Tree left;
private Tree right;
public Tree() {
}
public Tree(int value) {
this.value = value;
this.left = this.right = null;
}
public Tree(int value, Tree left, Tree right) {
this.value = value;
this.left = left;
this.right = right;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Tree getLeft() {
return left;
}
public void setLeft(Tree left) {
this.left = left;
}
public Tree getRight() {
return right;
}
public void setRight(Tree right) {
this.right = right;
}
}
public class Main {
public static void main(String[] args) {
Tree A = initA();
Tree B = initB();
System.out.println(hasSubTree(A, B));
}
public static Tree initA() {
Tree tree1 = new Tree(8);
Tree tree2 = new Tree(8);
Tree tree3 = new Tree(7);
Tree tree4 = new Tree(9);
Tree tree5 = new Tree(2);
Tree tree6 = new Tree(4);
Tree tree7 = new Tree(7);
tree1.setLeft(tree2);
tree1.setRight(tree3);
tree2.setLeft(tree4);
tree2.setRight(tree5);
tree5.setLeft(tree6);
tree5.setRight(tree7);
return tree1;
}
public static Tree initB() {
Tree tree1 = new Tree(8);
Tree tree2 = new Tree(9);
Tree tree3 = new Tree(2);
tree1.setLeft(tree2);
tree1.setRight(tree3);
return tree1;
}
public static boolean hasSubTree(Tree A, Tree B) {
boolean exist = false;
if (A != null && B != null) {
if (A.getValue() == B.getValue()) {
exist = doesTree1HaveTree2(A, B);
}
if (!exist) {
exist = hasSubTree(A.getLeft(), B);
}
if (!exist) {
exist = hasSubTree(A.getRight(), B);
}
}
return exist;
}
public static boolean doesTree1HaveTree2(Tree A, Tree B) {
if (B == null) {
return true;
}
if (A == null) {
return false;
}
if (A.getValue() != B.getValue()) {
return false;
}
return doesTree1HaveTree2(A.getLeft(), B.getLeft()) && doesTree1HaveTree2(A.getRight(), B.getRight());
}
}