二叉树(Binary tree)是树形结构的一个重要类型
在java中,可以把数的一个节点看成一个对象,每个节点都有data和最多两个字节点
class TreeNode {
int data;
TreeNode left;
TreeNode right;
}
首先先生成一颗二叉树
public void add(TreeNode node) {
if (node.data < this.data) {
if (left == null) left = node;
else left.add(node);
}
if (node.data > this.data) {
if (right == null) right = node;
else right.add(node);
}
}
public static void main(String[] args) {
Tree tree = new Tree();
tree.add(8);
tree.add(4);
tree.add(2);
tree.add(3);
tree.add(1);
tree.add(6);
tree.add(6);
tree.add(7);
tree.add(12);
tree.add(10);
tree.add(9);
tree.add(11);
tree.add(14);
tree.add(13);
tree.add(15);
}
创建的二叉树如下图所示
先根遍历:先根遍历就是先遍历根节点,然后遍历左子树,再然后右子树
即输出8->4->2->1->3->6->7->12->10->9->11->14->13->15
public void firstRoot() {
System.out.print(data + " ");
if (left != null) left.firstRoot();
if (right != null) right.firstRoot();
}
中根遍历,先遍历左子树,然后遍历根,再然后遍历右子树
即输出1->2->3->4->6->7->8->9->10->11->12->13->14->15
public void midRoot() {
if (left != null) left.midRoot();
System.out.print(data + " ");
if (right != null) right.midRoot();
}
后根遍历:先遍历左子树,然后再遍历右子树,最后再遍历根;
即输出:1->3->2->7->6->4->9->11->10->13->15->14->12->8
public void afterRoot() {
if (left != null) left.afterRoot();
if (right != null) right.afterRoot();
System.out.print(data + " ");
}
完整代码
public class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int data) {
this.data = data;
}
//中序存
public void add(TreeNode node) {
if (node.data < this.data) {
if (left == null) left = node;
else left.add(node);
}
if (node.data > this.data) {
if (right == null) right = node;
else right.add(node);
}
}
public void firstRoot() {
System.out.print(data + " ");
if (left != null) left.firstRoot();
if (right != null) right.firstRoot();
}
public void midRoot() {
if (left != null) left.midRoot();
System.out.print(data + "->");
if (right != null) right.midRoot();
}
public void afterRoot() {
if (left != null) left.afterRoot();
if (right != null) right.afterRoot();
System.out.print(data + "->");
}
}
public class Tree {
TreeNode root;
public void add(int n) {
TreeNode node = new TreeNode(n);
if (root == null) {
root = node;
} else {
root.add(node);
}
}
public void first() {
root.firstRoot();
System.out.println();
}
public void mid() {
root.midRoot();
System.out.println();
}
public void after() {
root.afterRoot();
System.out.println();
}
}