HDOJ-3999(二叉搜索树+先序遍历)

The order of a Tree

题解:建立一颗二叉搜索树,然后先序遍历



import java.util.Scanner;

public class Main3 {
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		while (cin.hasNext()) {
			int n = cin.nextInt();
			BinarySearchTree b = new BinarySearchTree();
			for (int i = 0; i < n; i++) {
				b.add(cin.nextInt());
			}
			b.show();
			b.answer();
			System.out.println();
		}
	}
}

class Node {
	public int data;
	public Node left;
	public Node right;

	public Node(int data) {
		this.data = data;
	}

	public Node() {
	}
}

class BinarySearchTree {

	private Node root;

	public void add(int val) {
		if (root == null) {
			root = new Node(val);
		} else {
			Node next = root;
			while (next != null) {
				if (val > next.data) {
					if (next.right == null) {
						next.right = new Node(val);
						break;
					} else {
						next = next.right;
					}
				} else {
					if (next.left == null) {
						next.left = new Node(val);
						break;
					} else {
						next = next.left;
					}
				}
			}
		}
	}

	public void show() {
		show(root);
	}

	private StringBuilder str = new StringBuilder();

	public void answer() {
		System.out.println(str.substring(0, str.length() - 1));
	}
	
	private void show(Node next) {
		str.append(next.data + " ");
		if (next.left != null) {
			show(next.left);
		}
		if (next.right != null) {
			show(next.right);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_39290830/article/details/85197994