二叉樹類的定義:
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());
}
}