问题表述:
二叉排序树,如果左子树不为空,那么左子树上所有节点的值均小于其根结点的值;如果右子树不为空,那么右子树所有节点的值均大于其根结点的值;左右子树也分别为二叉排序树。
代码实现:
class Node{
public int data;
public Node left;
public Node right;
public Node(int data){
this.data = data;
this.left = null;
this.right = null;
}
}
public class BinaryTree {
private Node root;
public BinaryTree(){
root = null;
}
//insert
public void insert(int data) {
Node newnode = new Node(data);
if (root==null) {
root = newnode;
}else {
Node current = root;
Node parent;
while (true) {
parent = current;
if (data<current.data) {
current = current.left;
if (current==null) {
parent.left = newnode;
return;
}
}else {
current = current.right;
if (current==null) {
parent.right = newnode;
return;
}
}
}
}
}
//build
public void buildTree(int[] data) {
for (int i = 0; i < data.length; i++) {
insert(data[i]);
}
}
//inOrder
public void inOrder(Node localRoot) {
if (localRoot!=null) {
inOrder(localRoot.left);
System.out.print(localRoot.data+" ");
inOrder(localRoot.right);
}
}
public void inOder() {
inOrder(this.root);
}
//preOrder
public void preOrder(Node localRoot) {
if (localRoot!=null) {
System.out.print(localRoot.data+" ");
preOrder(localRoot.left);
preOrder(localRoot.right);
}
}
private void preOrder() {
preOrder(this.root);
}
//postOrder
public void postOrder(Node localRoot) {
if (localRoot!=null) {
postOrder(localRoot.left);
postOrder(localRoot.right);
System.out.print(localRoot.data+" ");
}
}
public void postOrder() {
postOrder(this.root);
}
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
int[] data = {2,8,7,4,9,3,1,6,7,5};
binaryTree.buildTree(data);
System.out.print("inOrder is: ");
binaryTree.inOder();
System.out.println();
System.out.print("preOrder is: ");
binaryTree.preOrder();
System.out.println();
System.out.print("postOrder is: ");
binaryTree.postOrder();
System.out.println();
}
}
运行结果:
inOrder is: 1 2 3 4 5 6 7 7 8 9
preOrder is: 2 1 8 7 4 3 6 5 7 9
postOrder is: 1 3 5 6 4 7 7 9 8 2