剑指OFFER 面试题26(二叉树):树的子结构 (JAVA)

题目

输入两棵二叉树A和B,判断B是不是A的子结构。

思路

(1)在A中找到与B的根节点的值一样的节点R;

(2)判断A中以R为根结点的子树是否包含和B一样的结构。

代码

注意,当比较double的数值是否相等时,不能用“==”,而用下面代码中的函数equal,通过两数之差的绝对值小于一个很小的树来实现。

/*
class BinaryTreeNode{
	double val;
	BinaryTreeNode left;
	BinaryTreeNode right;
	BinaryTreeNode(double x) {val=x;}
}
*/
public class SubstructureInTree {
	public static boolean hassubtree(BinaryTreeNode root1, BinaryTreeNode root2) {
		
		boolean result=false;
		if (root1!=null && root2!=null) {
			/*
			if(equal(root1.val==root2.val)) {
				result=hassubtreecore(root1,root2);
			}
			if(!result) {
				result=hassubtree(root1.left,root2);
			}
			if(!result) {
				result=hassubtree(root1.right,root2);
			}
			*/
			//将上面几行直接写成几个结果“或”的形式
			result=hassubtreecore(root1,root2)||hassubtree(root1.left,root2)||hassubtree(root1.right,root2);
		
		}
		return result;

	}
	public static boolean hassubtreecore(BinaryTreeNode node1,BinaryTreeNode node2) {
		if (node2==null) {return true;}
		if (node1==null) {return false;}
		return equal(node1.val,node2.val) && hassubtreecore(node1.left, node2.left) && hassubtreecore(node1.right,node2.right);
	}
    //本题中BinaryTreeNode的值类型已经定义了int,实际上可以直接用“==”来判断两个节点的值是否相等。
	//但是如果val的类型为double时,就不能用“==”来比较,因为在计算机内表示小数时,(包括float 和double)都有误差。
	//判断两个小数是否相等,只能判断他们之差的绝对值是不是在一个很小的范围之内,因此定义equal函数。
	public 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) {
    	BinaryTreeNode root1 = new BinaryTreeNode(8);
    	BinaryTreeNode root2 = new BinaryTreeNode(8);
    	BinaryTreeNode root3 = new BinaryTreeNode(8);
    	BinaryTreeNode root4 = new BinaryTreeNode(2);
    	BinaryTreeNode node1 = new BinaryTreeNode(7);
    	BinaryTreeNode node2 = new BinaryTreeNode(9);
    	BinaryTreeNode node3 = new BinaryTreeNode(4);
    	BinaryTreeNode node4 = new BinaryTreeNode(7);
    	BinaryTreeNode node5 = new BinaryTreeNode(9);
    	BinaryTreeNode node6 = new BinaryTreeNode(2);
    	root1.left=root3;
    	root1.right=node1;
    	root3.left=node2;
    	root3.right=root4;
    	root4.left=node3;
    	root4.right=node4;
    	root2.left=node5;
    	root2.right=node6;
    	boolean result=hassubtree(root1,root2);
    	System.out.println(result);
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值