使用Java實現二叉樹及其遍歷操作
實現二叉樹 首先實現二叉樹的結點元素 此處結點元素定義爲樹結點的值和二叉樹結點類型的左孩子和右孩子
操作爲構建、遍歷操作(前序遍歷、中序遍歷、後續遍歷)
代碼如下
public class BinTree {
//二叉樹的定義、構建以及前中後序遍歷
int val;//the value of the node
BinTree lchild;//左子樹
BinTree rchild;//右子樹
BinTree(int x)
{
this.val=x;
}
public void Pretraverse(BinTree bt)//二叉樹的前序遍歷:root-left-right
{
BinTree temp=bt;
if(temp!=null)
{
System.out.print(temp.val+"->");
Pretraverse(bt.lchild);
Pretraverse(bt.rchild);
}
}
public void Intraverse(BinTree bt)//二叉樹的中序遍歷:left-root-right
{
BinTree temp=bt;
if(temp!=null)
{
Intraverse(bt.lchild);
System.out.print(temp.val+"->");
Intraverse(bt.rchild);
}
}
public void Posttraverse(BinTree bt)//二叉樹的後序遍歷:left-right-root
{
BinTree temp=bt;
if(temp!=null)
{
Posttraverse(bt.lchild);
Posttraverse(bt.rchild);
System.out.print(temp.val+"->");
}
}
public static void main(String[] args) {
//構建二叉樹
BinTree root=new BinTree(100);
root.lchild=new BinTree(50);
root.rchild=new BinTree(130);
root.lchild.lchild=new BinTree(35);
root.lchild.rchild=new BinTree(55);
root.rchild.lchild=new BinTree(105);
root.rchild.rchild=new BinTree(135);
//遍歷
System.out.println("前序遍歷");
root.Pretraverse(root);
System.out.println("\\");
System.out.println("中序遍歷");
root.Intraverse(root);
System.out.println("\\");
System.out.println("後序遍歷");
root.Posttraverse(root);
System.out.println("\\");
}
}
運行結果:
前序遍歷
100->50->35->55->130->105->135->\
中序遍歷
35->50->55->100->105->130->135->\
後序遍歷
35->55->50->105->135->130->100->\