二叉树类的定义:
public class BTree<T> {
private T data;
private BTree<T> leftChild;
private BTree<T> rightChild;
public BTree()
{
}
public BTree(T data, BTree<T> leftChild, BTree<T> rightChild) {
this.data = data;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public BTree<T> getLeftChild() {
return leftChild;
}
public void setLeftChild(BTree<T> leftChild) {
this.leftChild = leftChild;
}
public BTree<T> getRightChild() {
return rightChild;
}
public void setRightChild(BTree<T> rightChild) {
this.rightChild = rightChild;
}
}
深度优先遍历二叉树
前序遍历(DLR)的递归算法:
若二叉树为空,则算法结束,否则:
访问根结点;
前序遍历根结点的左子树;
前序遍历根结点的右子树。
广度优先遍历二叉树。
广度优先周游二叉树(层序遍历)是用队列来实现的,从二叉树的第一层(根结点)开始,自上至下逐层遍历;在同一层中,按照从左到右的顺序对结点逐一访问。
按照从根结点至叶结点、从左子树至右子树的次序访问二叉树的结点。算法:
1初始化一个队列,并把根结点入列队;
2当队列为非空时,循环执行步骤3到步骤5,否则执行6;
3出队列取得一个结点,访问该结点;
4若该结点的左子树为非空,则将该结点的左子树入队列;
5若该结点的右子树为非空,则将该结点的右子树入队列;
6结束。
public class BTreeList {
private static List<BTree<String>> binTree = new ArrayList<BTree<String>>();
public static void main(String[] args) {
BTreeList test = new BTreeList();
test.createBinTree();
//test.preOrder(binTree.get(0));
test.guangDuList(binTree.get(0));
}
/**
* 创建一棵二叉树
*/
public void createBinTree()
{
for(int i = 0; i < 64; i++)
{
binTree.add(new BTree<String>("节点" + i, null, null));
}
for(int i = 0; i < 64; i++)
{
int leftChildIndex = (2*i) + 1;
int rightChildIndex = (2*i) + 2;
if( leftChildIndex < binTree.size())
{
binTree.get(i).setLeftChild(binTree.get(2*i+1));
}
else
{
binTree.get(i).setLeftChild(null);
}
if(rightChildIndex < binTree.size())
{
binTree.get(i).setRightChild(binTree.get((2*i)+2));
}
else
{
binTree.get(i).setRightChild(null);
}
}
}
/**
*
* 广度遍历。
*/
public void guangDuList(BTree<String> rootElement)
{
ArrayDeque<BTree<String>> queue = new ArrayDeque<BTree<String>>();
queue.push(rootElement);
while(true)
{
if(queue.isEmpty())
{
break;
}
BTree<String> binTree = queue.pop();
System.out.println(binTree.getData());
if(binTree.getLeftChild() != null)
{
queue.push(binTree.getLeftChild());
}
if(binTree.getRightChild() != null)
{
queue.push(binTree.getRightChild());
}
}
}
/**
* 前序遍历。
*/
public void preOrder(BTree<String> binNode)
{
if(binNode == null)
{
return;
}
System.out.println(binNode.getData());
preOrder(binNode.getLeftChild());
preOrder(binNode.getRightChild());
}
}