public class E26Subtree {
//树的子结构
private class BinaryTreeNode{
//比较时要注意在精度范围内比较
double value;
BinaryTreeNode leftNode;
BinaryTreeNode rightNode;
}
public static boolean hasSubtree(BinaryTreeNode root1, BinaryTreeNode root2){
//找到相同节点
boolean result = false;
if (root1 != null && root2 != null){
//找到相同节点则判断是否为子树
if (doubleEqual(root1.value, root2.value))
result = hasSubtreeCore(root1, root2);
if (!result)
result = hasSubtreeCore(root1.leftNode, root2);
if (!result)
result = hasSubtreeCore(root1.rightNode, root2);
}
return result;
}
private static boolean hasSubtreeCore(BinaryTreeNode root1, BinaryTreeNode root2){
//判断是否为子树
if (root2 == null)
return true;
if (root1 == null)
return false;
if (!doubleEqual(root1.value, root2.value))
return false;
return hasSubtreeCore(root1.leftNode, root2.leftNode) &&
hasSubtreeCore(root1.rightNode, root2.rightNode);
}
private static boolean doubleEqual(double a, double b){
return (a - b) > -0.0000001 && (a - b) < 0.0000001;
}
//测试用例
public static void main(String[] args){
/*空二叉树
*只含一个节点
* 全为左节点
* 全为右节点
* 一般二叉树*/
}
}
树的子结构(Java实现)
最新推荐文章于 2023-04-17 10:48:49 发布