[面试题]Amazon: Given two binary trees,if the first tree is subtree of the second one

Given two binary trees, check if the first tree is subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.


两个树,先写另一个函数:isIdentical, 

用递归的方式:如何判断两个树是否完全一样呢?那就看从根开始,所有节点的值都相等。


写好了这个,就简单了。 给两个树的根,如何都相等,root就是root2的子树,反之,我们还要查看其他节点,要检查的子树root不变,看left和right树。

继续递归,只要找到一个相等的,那就是有子树。思路其实很简单,就是不要把这个问题放到一个递归里,比较麻烦。 我要是放一起考虑,就感觉会脑残。 


public static boolean isSubTree(TreeNode root,TreeNode root2){
		
		 if(root==null) return true;
		 if(root2==null) return false;
	
			if(isIdentical(root,root2)) return true;
			else {
				return isIdentical(root,root2.left)||isIdentical(root,root2.right);
			}
		
		  
		
	}
	public static boolean isIdentical(TreeNode root,TreeNode root2){
		
		if(root==null&&root2==null) return true;
		if(root==null||root2==null) return false;
		
		if(root.val==root2.val) {
			return isSubTree(root.left,root2.left)&&isSubTree(root.right,root2.right);
		}
		else return false;
		
	}

public class TreeNode {

	int val;
	TreeNode left;
	TreeNode right;
	TreeNode(int x){
		val=x;
	}

}


主函数test case:

public static void main(String[] args) {
		// TODO Auto-generated method stub
			TreeNode root=new TreeNode(10);
			root.left=new TreeNode(4);
			root.right=new TreeNode(6);
			root.left.right=new TreeNode(30);
			
			TreeNode root2=new TreeNode(26);
			root2.left=new TreeNode(10);
			root2.left.left=new TreeNode(4);
			root2.left.right=new TreeNode(6);
			root2.right=new TreeNode(6);
			root2.left.left.right=new TreeNode(30);
			root2.right=new TreeNode(3);
			root2.right.right=new TreeNode(3);
			
			System.out.println(isSubTree(root,root2));
			//System.out.println(isIdentical(root,root2));
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值