树结构及前中后续遍历
public class Tree {
public static void main(String[] args) {
Tree root = new Tree(50);
Tree.insert(root, 30);
Tree.insert(root, 60);
Tree.insert(root, 70);
Tree.insert(root, 100);
Tree.insert(root, 80);
Tree.VLR(root);
System.out.println();
Tree.LDR(root);
System.out.println();
Tree.LRD(root);
}
/**数元素*/
int item;
/**左节点*/
Tree left;
/**右节点*/
Tree right;
/**构造函数*/
public Tree(int e) {
this.item = e;
this.left = null;
this.right = null;
}
/**获取元素*/
public int getItem() {
return item;
}
/**插入元素*/
public static void insert(Tree root, int value) {
if(root.item < value) {
if (root.right == null) {
root.right = new Tree(value);
} else {
insert(root.right, value);
}
} else {
if (root.left == null) {
root.left = new Tree(value);
} else {
insert(root.left, value);
}
}
}
/**前序排序-VLR*/
public static void VLR(Tree root) {
print(root);
if (root.left != null) {
VLR(root.left);
}
if (root.right != null) {
VLR(root.right);
}
}
/**中序排序-LDR*/
public static void LDR(Tree root) {
if (root.left != null) {
LDR(root.left);
}
print(root);
if (root.right != null) {
LDR(root.right);
}
}
/**后序排序-LRD*/
public static void LRD(Tree root) {
if (root.left != null) {
LRD(root.left);
}
if (root.right != null) {
LRD(root.right);
}
print(root);
}
/**打印*/
private static void print(Tree root) {
System.out.print(root.getItem() + " ");
}
}
缘于生活,而归于工作。本人所书,而意于分享。
如有转载,请注明出处!
--活出自己范儿

浙公网安备 33010602011771号