题目
输入两颗树A和B,判断B是不是A的子结构;
public static class TreeNode{
public double val;//注意节点值为double
TreeNode left=null;
TreeNode right=null;
public TreeNode(int val) {
this.val = val;
}
}
思路
1)先对A树进行遍历,找到与B树的根结点值相同的结点R;
2)判断A树中以R为根结点的子树是否包含B树一样的结构。
测试用例
1.功能测试(A、B为普通二叉树;B是或者不是A树的子结构)
2.特殊测试(任意一个或者两个树的根结点为null;左斜树;右斜树)
代码
public class subTree {
public static class TreeNode{
public double val;
TreeNode left=null;
TreeNode right=null;
public TreeNode(int val) {
this.val = val;
}
}
public static void constructTree(TreeNode root,TreeNode left,TreeNode right){
root.left=left;
root.right=right;
}
//1.对每个节点进行遍历判断
public static boolean hasSubTree(TreeNode root1,TreeNode root2){
if(root1==null||root2==null)
return false;
boolean result=false;
if(equal(root1.val,root2.val)){
result=doseTreeBIsSubTree(root1,root2);
if(!result){
result=hasSubTree(root1.left,root2)||hasSubTree(root1.right,root2);
}
}
return result;
}
//2.判断root节点开始的子树中各个节点是否相同
private static boolean doseTreeBIsSubTree(TreeNode root1,TreeNode root2){
if(root2==null) return true;
if (root1==null)return false;
return equal(root1.val,root2.val)&&doseTreeBIsSubTree(root1.left,root2.left)&&doseTreeBIsSubTree(root1.right,root2.right);
}
//判断两个浮点数是否相同
private static boolean equal(double num1,double num2){
if(num1-num2<0.0000001&&num1-num2>-0.0000001){
return true;
}
return false;
}
public static void main(String[] args) {
TreeNode Aa1=new TreeNode(8);
TreeNode Aa21=new TreeNode(8);
TreeNode Aa22=new TreeNode(7);
TreeNode Aa31=new TreeNode(9);
TreeNode Aa32=new TreeNode(2);
TreeNode Aa43=new TreeNode(4);
TreeNode Aa44=new TreeNode(7);
constructTree(Aa1,Aa21,Aa22);
constructTree(Aa21,Aa31,Aa32);
constructTree(Aa32,Aa43,Aa44);
TreeNode Bb1=new TreeNode(8);
TreeNode Bb21=new TreeNode(9);
TreeNode Bb22=new TreeNode(2);
constructTree(Bb1,Bb21,Bb22);
System.out.println(hasSubTree(Aa1,Bb1));
}
}
代码优化
boolean result=false;
if(equal(root1.val,root2.val)){
result=doseTreeBIsSubTree(root1,root2);
if(!result){
result=hasSubTree(root1.left,root2)||hasSubTree(root1.right,root2);
}
}
return result;
可以改为
return doesTree1HasTree2(root1, root2)|| hasSubtree(root1.left, root2)
||hasSubtree(root1.right, root2);