Cracking the coding interview--Q4.7

原文:

You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1

译文:

有两棵很大的二叉树:T1有上百万个结点,T2有上百个结点。写程序判断T2是否为T1的子树。


方法:


把T1,T2两颗树转换成字符串,如[head.data [左子树] [右子树]],同时左右子树以相同的方法转换。

如果左子树或者右子树存在一颗并且只为一颗子树为空,则该子树设置为[null],这样就能区分左子树或者右子树

然后判断T2是否为T1的子串即可。


package chapter_4_TreesandGraphs;

import java.util.Scanner;

/**
 * 
 * 有两棵很大的二叉树:T1有上百万个结点,T2有上百个结点。写程序判断T2是否为T1的子树。
 * 
 */
public class Question_4_7 {
	private static Node_4_6 t2Parent;
	
	public static void insertTreeNode(Node_4_6 curNode, Node_4_6 node) {
		if(node.data < curNode.data) {
			if(curNode.lchild != null) {
				insertTreeNode(curNode.lchild, node);
			} else{
				curNode.lchild = node;
				node.parent = curNode;
			}
		} else {
			if(curNode.rchild != null) {
				insertTreeNode(curNode.rchild, node);
			} else {
				curNode.rchild = node;
				node.parent = curNode;
			}
		}
	}
	
	public static void createTree(Node_4_6 head, int array[]) {
		int len = array.length;
		int curIndex = 1;
		while(curIndex < len) {
			Node_4_6 node = new Node_4_6();
			node.data = array[curIndex];
			if(node.data == 1) {
				t2Parent = node;
				System.out.println("set t2Parent.data = " + node.data);
			} 
			node.lchild = null;
			node.rchild = null;
			insertTreeNode(head, node);
			curIndex ++;
		}
	}
	
	/**
	 * @param node
	 * @return
	 * 
	 * 把树转换成字符串
	 * 
	 */
	public static String tranceString(Node_4_6 node) {
		if(node == null) {
			return "[null]";
		} else {
			if(node.lchild!=null || node.rchild!=null) {
				return "[" + node.data + tranceString(node.lchild) + tranceString(node.rchild) + "]";
			} else {
				return "[" + node.data + "]";
			}
		}
	}
	
	public static void main(String args[]) {
		Scanner scanner = new Scanner(System.in);
		String string = scanner.nextLine();
		// 7 10 1 3 6 5 4 2 8
		String strs[] = string.split(" ");
		int array[] = new int[strs.length];
		for(int i=0; i<array.length; i++) {
			array[i] = Integer.parseInt(strs[i]);
		}
		
		Node_4_6 head = new Node_4_6();
		head.data = array[0];
		head.lchild = null;
		head.rchild = null;
		
		createTree(head, array);
		
		String pattern1 = tranceString(head);
		
		String pattern2 = tranceString(t2Parent);
		
		System.out.println("T1 转换 :" + pattern1);
		System.out.println("T2 转换 :" + pattern2);
		
		System.out.println(pattern2 + "  是否为  " + pattern1 + " 子串");
		
		System.out.println(pattern1.contains(pattern2));
	}
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值