1、先序遍历
我的理解就是 先根节点,然后在左子树,右子树
代码
void PreorderTraversal( BinTree BT ){
if (BT == NULL)
return ;
//前序遍历
printf(" %c", BT -> Data);
PreorderTraversal(BT -> Left);
PreorderTraversal(BT -> Right);
}
2、中序遍历
就是先根节点的左子树,然后根节点 然后是右子树
代码
void InorderTraversal( BinTree BT ){
if (BT == NULL)
return;
//中序遍历
InorderTraversal(BT -> Left);
printf(" %c", BT -> Data);
InorderTraversal(BT -> Right);
}
3、后序遍历
就是先左子树,然后右子树,最后根节点
//后序遍历
PostorderTraversal(BT -> Left);
PostorderTraversal(BT -> Right);
printf(" %c", BT -> Data);
}
4、层序遍历
一层一层的遍历下去
void LevelOrder(BinT BT){
queue<BinT>q;//定义一个结点类型的队列
int flog = 1;
if(BT){
BinT temp;//定义一个结点用来存队列中的第一个结点
q.push(BT);//放入根节点 这个时候队列一定不会是空的
while(!q.empty()){
temp = q.front();//把对立的第一个元素,给temp;
q.pop();//删除队列第一个元素
//输出这个树结点的值
if (flog) cout << temp->data, flog = 0;
else cout << " " << temp->data;
//将这个结点的左右还在放进队列(如过有的话)
if (temp->left != NULL) q.push(temp->left);
if (temp->right != NULL) q.push(temp->right);
}
}
}