public class BinaryTree {
private static TreeNode root;
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
binaryTree.insert(2);
binaryTree.insert(1);
binaryTree.insert(3);
binaryTree.preOrder(root);
System.out.println();
binaryTree.inOrder(root);
System.out.println();
binaryTree.postOrder(root);
}
public void insert(int value) {
if (root == null) {
root = new TreeNode(value);
return;
}
TreeNode cur = root; //当前遍历到的节点
TreeNode parent = root; //遍历到的节点的父节点
boolean isLeft = true; //是否添加到左侧
while (cur != null) {
parent = cur;
if (value < cur.value) {
isLeft = true;
cur = cur.left;
} else {
isLeft = false;
cur = cur.right;
}
}
TreeNode treeNode = new TreeNode(value);
if (isLeft) {
parent.left = treeNode;
} else {
parent.right = treeNode;
}
}
public void preOrder(TreeNode treeNode) {//先序:根左右
if (treeNode != null) {
System.out.print(treeNode.value + " ");
preOrder(treeNode.left);
preOrder(treeNode.right);
}
}
public void inOrder(TreeNode treeNode) {//中序:左根右
if (treeNode != null) {
inOrder(treeNode.left);
System.out.print(treeNode.value + " ");
inOrder(treeNode.right);
}
}
public void postOrder(TreeNode treeNode) {//后序:左右根
if (treeNode != null) {
postOrder(treeNode.left);
postOrder(treeNode.right);
System.out.print(treeNode.value + " ");
}
}
public static class TreeNode {
int value;
TreeNode left;
TreeNode right;
public TreeNode(int value) {
this.value = value;
}
}
}
测试:
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
binaryTree.insert(2);
binaryTree.insert(1);
binaryTree.insert(3);
binaryTree.preOrder(root);
System.out.println();
binaryTree.inOrder(root);
System.out.println();
binaryTree.postOrder(root);
}
结果