25.输入两个二叉树,判断B树是不是A树的子结构

package java2019;
//输入两个二叉树,判断B树是不是A树的子结构
public class Demo25 {
	public static boolean HasSubtree(TreeNode root1,TreeNode root2){
		boolean result = false;
		//当Tree1和Tree2都不为null,才进行比较。否则直接返回false
		if(root2!=null && root1!=null){
			//如果找到了对应Tree2的根节点的点
			if(root1.val==root2.val){
				//以这个根节点为起点判断是否包含Tree2
				result = doseTree1HaveTree2(root1,root2);
			}
			//如果找不到,那么就再去root的左儿子当做起点,去判断是否包含Tree2
			if(!result){
				result = HasSubtree(root1.left,root2);
			}
			//如果还找不到,那么就再去root的右儿子当做起点,去判断是否包含Tree2
			if(!result){
				result = HasSubtree(root1.right,root2);
			}
		}
		//返回结果
		return result;
	}
	
	public static boolean doseTree1HaveTree2(TreeNode node1,TreeNode node2){
		//如果Tree2已经遍历完了都能对应得上,返回true
		if(node2 == null){
			return true;
		}
		//如果Tree2还没有遍历完,Tree1却遍历完了。返回false
		if(node1 == null){
			return false;
		}
		//如果其中有一个点没有对应上,返回false
		if(node1.val!=node2.val){
			return false;
		}
		//如果根节点对应得上,那么就分别去子节点里面匹配
		return doseTree1HaveTree2(node1.left,node2.left) &&
				doseTree1HaveTree2(node1.right,node2.right);
	}
	public static void main(String[] args) {
		TreeNode root1 = new TreeNode(5);
		TreeNode n1 = new TreeNode(3);
		TreeNode n2 = new TreeNode(10);
		TreeNode n3 = new TreeNode(1);
		TreeNode n4 = new TreeNode(4);
		TreeNode n5 = new TreeNode(6);
		TreeNode n6 = new TreeNode(11);
		
		root1.left=n1;
		root1.right=n2;
		n1.left=n3;
		n1.right=n4;
		n2.left=n5;
		n2.right=n6;
		System.out.println(HasSubtree(root1,n5));
	}

}

你可能感兴趣的:(数据结构)