二叉树的概念
二叉树(Binary Tree)是个有限元素的集合,该集合或者为空、或者由一个称为根(root)的元素及两个不相交的、被分别称为左子树和右子树的二叉树组成。当集合为空时,称该二叉树为空二叉树。在二叉树中,一个元素也称作一个结点。
现在我们给出一组二叉树
二叉树遍历又分为先序遍历(根节点-左子树 -右子树 )、中序遍历(左子树 -根节点-右子树)、后序遍历(左子树-右子树-根节点)
上述二叉树的先中后遍历结果分别为
先序遍历:12---9---76---35---22---16---48---46---40---90
中序遍历:9---12---16---22---35---40---46---48---76---90
后序遍历:9---16---22---40---46---48---35---90---76---12
首先我们定义一个二叉树数据结构的类
<pre name="code" class="java">class Node {
int data; // 根节点数据
Node left; // 左子树
Node right; // 右子树
public Node(int data) // 实例化二叉树类
{
this.data = data;
left = null;
right = null;
}
//{ 12, 76, 35, 22, 16, 48, 90, 46, 9, 40};
public void insert(Node root, int data) { // 向二叉树中插入子节点
if (data > root.data) // 二叉树的左节点都比根节点小
{
if (root.right == null) {
root.right = new Node(data);
}
else{
this.insert(root.right, data);
}
}
else
{ // 二叉树的右节点都比根节点大
if (root.left == null) {
root.left = new Node(data);
}
else {
this.insert(root.left, data);
}
}
}
}
遍历二叉树
<pre name="code" class="java">public class BinaryTree {
public static void preOrder(Node root) {
if (root != null) {
System.out.print(root.data + "-");
preOrder(root.left);
preOrder(root.right);
}
}
public static void inOrder(Node root) {
if (root != null) {
inOrder(root.left);
System.out.print(root.data + "--");
inOrder(root.right);
}
}
public static void postOrder(Node root) {
if (root != null) {
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data + "---");
}
}
public static void main(String[] str) {
int[] array = { 12, 76, 35, 22, 16, 48, 90, 46, 9, 40 };
Node root = new Node(array[0]); // 创建二叉树
for (int i = 1; i < array.length; i++) {
root.insert(root, array[i]); // 向二叉树中插入数据
}
System.out.println("先序遍历:");
preOrder(root);
System.out.println();
System.out.println("中序遍历:");
inOrder(root);
System.out.println();
System.out.println("后序遍历:");
postOrder(root);
}
}
打印结果:
先序遍历:
12-9-76-35-22-16-48-46-40-90-
中序遍历:
9--12--16--22--35--40--46--48--76--90--
后序遍历:
9---16---22---40---46---48---35---90---76---12---