您的位置:首页 > 其它

Cracking the coding interview--Q4.7

2014-11-17 21:16 351 查看
原文:

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));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法