创建节点类:
package org.binary;
public class Node {
Node left;
Node right;
int data;
public Node(int data) {
this.data = data;
}
}
创建二叉树操作类:
package org.binary;
public class BinaryTree {Node root;
public void insert(int data) {root = insert(root, data);}
private Node insert(Node node, int data) {// 如果node为null那么首先创建一个node对象if (node == null) {node = new Node(data);} else {if (data <= node.data) {node.left = insert(node.left, data);} else {node.right = insert(node.right, data);}}
return node;}
public void printTree() {this.printTree(root);}
private void printTree(Node node) {if (node == null)return;printTree(node.left);System.out.print(node.data + " ");printTree(node.right);}}
创建测试类:
package org.binary;
public class Test {public static void main(String[] args) {int[] arrys = { 56, 23, 57, 79, 34, 23, 57, 67, 22, 89 };BinaryTree binaryTree = new BinaryTree();for (int i = 0; i < arrys.length; i++) {binaryTree.insert(arrys[i]);}binaryTree.printTree();}}
输出结果:
22 23 23 34 56 57 57 67 79 89