Huazhong University of Science and Technology binary sort tree (java)

题目描述
输入一系列整数,建立二叉排序树,并进行前序,中序,后序遍历。
输入描述:
输入第一行包括一个整数n(1<=n<=100)。
接下来的一行包括n个整数。
输出描述:
可能有多组测试数据,对于每组数据,将题目所给数据建立一个二叉排序树,并对二叉排序树进行前序、中序和后序遍历。
每种遍历结果输出一行。每行最后一个数据之后有一个空格。

输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。
示例1
输入
复制
5
1 6 5 9 8
输出
复制
1 6 5 9 8 
1 5 6 8 9 
5 8 9 6 1 
import java.util.*;
import java.io.*;
import java.text.* ;
public class Main
{
	static int n;
	static int m;
	static int[][] matrix;
	static int res = Integer.MAX_VALUE;
    public static void main(String[] args){
    	try {
	        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
	        while((br.readLine()) != null) {
	        	String[] parts = br.readLine().split(" ");
	        	int len = parts.length;
	        	int[] num = new int[len];
	        	for(int i = 0; i < len; i++) {
	        		num[i] = Integer.parseInt(parts[i]);
	        	}
	        	BiTNode root = new BiTNode(num[0]);
	        	for(int i = 1; i < len; i++) {
	        		arrayToTree(root, num[i]);
	        	}
	        	printTreePreOrder(root);
	        	System.out.println();
	        	printTreeInOrder(root);
	        	System.out.println();
	        	printTreePostOrder(root);
	        	System.out.println();
	        }
 	    } catch (IOException e) {
	        e.printStackTrace();
	    }
    }
    static void arrayToTree(BiTNode root, int num) {
    	if(num == root.data) return;
    	if(num > root.data) {
    		if(root.rchild == null) root.rchild = new BiTNode(num);
    		else arrayToTree(root.rchild, num);
    	}
    	else {
    		if(root.lchild == null) root.lchild = new BiTNode(num);
    		else arrayToTree(root.lchild, num);
    	}
    }
    static void printTreePreOrder(BiTNode root) {
    	if(root != null) {
    		System.out.print(root.data+" ");
    		printTreePreOrder(root.lchild);
    		printTreePreOrder(root.rchild);
    	}
    }
    static void printTreeInOrder(BiTNode root) {
    	if(root != null) {
    		printTreeInOrder(root.lchild);
    		System.out.print(root.data+" ");
    		printTreeInOrder(root.rchild);
    	}
    }
    static void printTreePostOrder(BiTNode root) {
    	if(root != null) {
    		printTreePostOrder(root.lchild);
    		printTreePostOrder(root.rchild);
    		System.out.print(root.data+" ");
    	}
    }
}
class BiTNode{
	 int data;
	 BiTNode lchild, rchild;
	 BiTNode(int x){
		 data = x;
	 }
}


Published 231 original articles · won praise 22 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43306331/article/details/104219059