1. 程式人生 > >DS二叉排序樹之建立和插入

DS二叉排序樹之建立和插入

DS二叉排序樹之建立和插入

時間限制: 1 Sec  記憶體限制: 128 MB 【Java有三倍的時間和記憶體限制】

題目描述

給出一個數據序列,建立二叉排序樹,並實現插入功能

對二叉排序樹進行中序遍歷,可以得到有序的資料序列

輸入

第一行輸入t,表示有t個數據序列

第二行輸入n,表示首個序列包含n個數據

第三行輸入n個數據,都是自然數且互不相同,資料之間用空格隔開

第四行輸入m,表示要插入m個數據

從第五行起,輸入m行,每行一個要插入的資料,都是自然數且和前面的資料不等

以此類推輸入下一個示例

輸出

第一行輸出有序的資料序列,對二叉排序樹進行中序遍歷可以得到

從第二行起,輸出插入第m個數據後的有序序列,輸出m行

以此類推輸出下一個示例的結果

 

樣例輸入

1

6

22 33  55  66  11  44

3

77

50

10

樣例輸出

11 22 33 44 55 66

11 22 33 44 55 66 77

11 22 33 44 50 55 66 77

10 11 22 33 44 50 55 66 77

 Solution:

由於上傳的程式碼不能由中文註釋,且為了趕時間,就沒有新增英文註釋,等後續回顧再進行解釋說明。

import java.util.*;
public class Main{
	public static void main(String args[]){
		Scanner scanner = new Scanner(System.in);
		int t = scanner.nextInt();
		for (int i = 0; i <t ; i++) {
			BST bst = new BST();
			int n = scanner.nextInt();
			for (int j = 0; j <n ; j++) {
				bst.add(new Node(scanner.nextInt()));
			}
			bst.midShow();
			System.out.println();
			int m = scanner.nextInt();
			for (int j = 0; j <m ; j++) {
				bst.add(new Node(scanner.nextInt()));
				bst.midShow();
				if (j!=m-1) System.out.println();
			}
		}
	}
}

class Node{
	int value;
	Node left;
	Node right;
	public Node(int value){
		this.value = value;
	}
	public void add(Node node){
		if (node == null){
			return;
		}
		if (node.value<this.value){
			if (this.left == null){
				this.left = node;
			}else {
				this.left.add(node);
			}
		}else {
			if (this.right== null){
				this.right = node;
			}else {
				this.right.add(node);
			}
		}
	}
	public void midShow(Node node){
		if (node == null){
			return;
		}
		midShow(node.left);
		System.out.print(node.value+" ");
		midShow(node.right);
	}
}

class BST{
	Node root;
	public void add(Node node){
		if (root == null){
			root =node;
		}else {
			root.add(node);
		}
	}
	public void midShow(){
		if (root!=null){
			root.midShow(root);
		}
	}
}