C++版
思路:将每一个节点都看成一棵树,然后做两件事 A:查看此树是否为空,为空则将值赋给此节点,将左右指针赋空值 B:此树不为空,则判断左孩子是否为空调用A步骤,右孩子同理
#include <iostream>
#include <cstdio>
using namespace std;
//树结构
struct BiTree
{
int v;
BiTree *lchild;
BiTree *rchild;
};
//构建树
BiTree *build(BiTree *root,int v)
{
if(root == NULL)
{
root = new BiTree();
root->v = v;
root->lchild = root->rchild = NULL;
}else if(root->v >= v)
root->lchild = build(root->lchild,v);
else
root->rchild = build(root->rchild,v);
return root;
}
//遍历二叉树
//前序遍历
void PreOrderTraverse(BiTree *T)
{
if(T){
printf("%d ",T->v);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
//中序遍历
void InOrderTraverse(BiTree *T)
{
if(T){
InOrderTraverse(T->lchild);
printf("%d ",T->v);
InOrderTraverse(T->rchild);
}
}
//后序遍历
void PostOrderTraverse(BiTree *T)
{
if(T){
PostOrderTraverse(T->lchild);
PostOrderTraverse(T->rchild);
printf("%d ",T->v);
}
}
int main()
{
BiTree *bt = NULL;
bt = build(bt,100);
bt = build(bt,50);
bt = build(bt,30);
bt = build(bt,78);
//输出遍历结果
printf("前序遍历:\n");
PreOrderTraverse(bt);
printf("\n中序遍历:\n");
InOrderTraverse(bt);
printf("\n后序遍历:\n");
PostOrderTraverse(bt);
return 0;
}
Java版
class BT
{
private int v;
private BT left;
private BT right;
public BT(int x){v = x;}
public void add(BT the)
{
if(the.v<v)
{
if(left==null)
left = the;
else
left.add(the);
}else
{
if(right==null)
right=the;
else
right.add(the);
}
}
//中序遍历
public void mid_trav()
{
if(left!=null) left.mid_trav();
System.out.println(v);
if(right!=null)right.mid_trav();
}
}
public class BiTree {
public static void main(String[] args)
{
BT bt = new BT(100);
bt.add(new BT(50));
bt.add(new BT(55));
bt.add(new BT(30));
bt.mid_trav();
}
}