二叉树遍历

来源:互联网 发布:java判断字符串为空格 编辑:程序博客网 时间:2024/06/16 17:15

一、基本概念

每个结点最多有两棵子树,左子树和右子树,次序不可以颠倒。

性质:

1、非空二叉树的第n层上至多有2^(n-1)个元素。

2、深度为h的二叉树至多有2^h-1个结点。

满二叉树:所有终端都在同一层次,且非终端结点的度数为2。

在满二叉树中若其深度为h,则其所包含的结点数必为2^h-1。

完全二叉树:除了最大的层次即成为一颗满二叉树且层次最大那层所有的结点均向左靠齐,即集中在左面的位置上,不能有空位置。

对于完全二叉树,设一个结点为i则其父节点为i/2,2i为左子节点,2i+1为右子节点。


二、二叉树的遍历

遍历即将树的所有结点访问且仅访问一次。按照根节点位置的不同分为前序遍历,中序遍历,后序遍历。
前序遍历:根节点->左子树->右子树
中序遍历:左子树->根节点->右子树

后序遍历:左子树->右子树->根节点

例如:求下面树的三种遍历
 
前序遍历:abdefgc
中序遍历:debgfac

后序遍历:edgfbca



今天练习用java实现二叉树的遍历算法,首先我先编写二叉树类BinaryTree,代码如下:


package test;


/**
 * @description
 * @date 2017-10-17下午3:31:31
 * @author Administrator
 */
public class BinaryTree {
int data; // 根节点数据
BinaryTree left; // 左子树
BinaryTree right; // 右子树


public BinaryTree(int data) // 实例化二叉树类
{
this.data = data;
left = null;
right = null;
}


public void insert(BinaryTree root, int data) { // 向二叉树中插入子节点
if (data > root.data) // 二叉树的右节点都比根节点大
{
if (root.right == null) {
root.right = new BinaryTree(data);
} else {
this.insert(root.right, data);
}
} else { // 二叉树的左节点都比根节点小
if (root.left == null) {
root.left = new BinaryTree(data);
} else {
this.insert(root.left, data);
}
}
}
}

当建立好二叉树类后可以创建二叉树实例,并实现二叉树的先根遍历,中根遍历,后根遍历,代码如下:


package test;


/**
 * @description
 * @date 2017-10-17下午3:33:58
 * @author Administrator
 */
public class BinaryTreePreorder {
public static void preOrder(BinaryTree root) { // 先根遍历
if (root != null) {
System.out.print(root.data + "-");
preOrder(root.left);
preOrder(root.right);
}
}


public static void inOrder(BinaryTree root) { // 中根遍历


if (root != null) {
inOrder(root.left);
System.out.print(root.data + "--");
inOrder(root.right);
}
}


public static void postOrder(BinaryTree 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 };
BinaryTree root = new BinaryTree(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---

原创粉丝点击