二叉树
二叉树概念
http://sjjp.tjuci.edu.cn/sjjg/DataStructure/DS/web/shu/shu6.1.1.2.htm
代码实现
package com.data.tree;
import java.util.ArrayList;
import java.util.List;
//链表形式遍历二叉树
public class BinaryTree {
private BinaryTree left;
private BinaryTree right;
private String data;
public BinaryTree(String data) {
this.data = data;
left = right = null;
}
// 链表形式先根次序遍历
public void PreorderTraversal(BinaryTree tree) {
if (tree != null) {
System.out.println(tree.data);
PreorderTraversal(tree.left);
PreorderTraversal(tree.right);
}
}
// 链表形式中根次序遍历二叉树
public void InorderTraversal(BinaryTree p) {
if (p != null) {
InorderTraversal(p.left);
System.out.print(p.data + " ");
InorderTraversal(p.right);
}
}
//链表形式后根次序遍历二叉树
public void PostorderTraversal(BinaryTree p) {
if (p != null) {
PostorderTraversal(p.left);
PostorderTraversal(p.right);
System.out.print(p.data + " ");
}
}
//集合存储层次遍历二叉树
public void traverseList(BinaryTree t)
{
List<BinaryTree> trees=new ArrayList<BinaryTree>();
trees.add(t);
int num=1;
for(int i=0;i<num;i++)
{
BinaryTree tree = trees.get(i);
System.out.println(tree.data);
if(tree.left!=null)
{
trees.add(tree.left);
num++;
}
if(tree.right!=null)
{
trees.add(tree.right);
num++;
}
}
}
//数组存储层次遍历二叉树
void traverseArray(BinaryTree t)
{
BinaryTree[] q=new BinaryTree[100];
q[0]=t;
int head=0;
int tail=1;
int i;
BinaryTree p;
while(head<tail)
{
p=q[head++];
System.out.println(p.data);
if(p.left!=null)
{
q[tail++]=p.left;
}
if(p.right!=null)
{
q[tail++]=p.right;
}
}
}
}