题目1009:二叉搜索树
时间限制:1 秒
内存限制:32 兆
特殊判题:否
提交:4111
解决:1836
-
题目描述:
-
判断两序列是否为同一二叉搜索树序列
-
输入:
-
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
-
输出:
-
如果序列相同则输出YES,否则输出NO
-
样例输入:
-
2 567432 543267 576342 0
-
样例输出:
-
YES NO
import java.util.Scanner; public class Main{ /** * @param args */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while( scanner.hasNext() ){ int n = scanner.nextInt(); if(n == 0){ break; } char souArray[] = scanner.next().toCharArray(); Node tree1 = null; for (int i = 0; i < souArray.length; i++) { tree1 = insertTree(tree1, souArray[i]); } Node tree[] = new Node[n]; for (int i = 0; i < n; i++) { char array[] = scanner.next().toCharArray(); for (int j = 0; j < array.length; j++) { tree[i] = insertTree(tree[i],array[j]); } } for (int i = 0; i < n; i++) { if(prePrintf(tree[i], "").equals(prePrintf(tree1, "")) && inPrintf(tree[i], "").equals(inPrintf(tree1, ""))){ System.out.println("YES"); }else{ System.out.println("NO"); } } } } private static Node insertTree(Node node, char c) { if(node == null){ node = new Node(); node.setKey(c); return node; }else{ if(c < node.getKey()){ node.setlChild( insertTree(node.getlChild(),c) ); } if( c > node.getKey() ){ node.setrChild( insertTree(node.getrChild(),c) ); } } return node; } public static String prePrintf(Node tree, String s){ s += tree.getKey(); if(tree.getlChild() != null){ s = prePrintf(tree.getlChild(),s); } if(tree.getrChild() != null){ s = prePrintf(tree.getrChild(),s); } return s; } public static String inPrintf(Node tree, String s){ if(tree.getlChild() != null){ s = inPrintf(tree.getlChild(),s); } s += tree.getKey(); if(tree.getrChild() != null){ s = inPrintf(tree.getrChild(),s); } return s; } public static String postPrintf(Node tree, String s){ if(tree.getlChild() != null){ s = postPrintf(tree.getlChild(), s); } if(tree.getrChild() != null){ s = postPrintf(tree.getrChild(), s); } s += tree.getKey(); return s; } public static class Node{ Node lChild; Node rChild; char key; public Node getlChild() { return lChild; } public void setlChild(Node lChild) { this.lChild = lChild; } public Node getrChild() { return rChild; } public void setrChild(Node rChild) { this.rChild = rChild; } public char getKey() { return key; } public void setKey(char key) { this.key = key; } } } /************************************************************** Problem: 1009 User: yihukurama Language: Java Result: Accepted Time:90 ms Memory:15556 kb ****************************************************************/