先序遍历:
void preorder(node* root)
{
if(root != NULL)
{
Visit(root); //假设Visit()函数已经定义;
preorder(root->lchild);
preorder(root->rchild);
}
}
中序遍历:
void inorder(node* root)
{
if(root != NULL)
{
inorder(root->lchild);
Visit(root);
inorder(root->rchild);
}
}
后续遍历:
void postorder(node* root)
{
if(root != NULL)
{
postorder(root->lchild);
postorder(root->rchild);
Visit(root);
}
}
层次遍历:
void level(node* root)
{
int front,rear;
node *que[maxsize]; //首先定义一个循环队列,用来记录将要访问层次上的节点;
front = rear = 0;
node *p;
if(root != NULL)
{
rear = (rear+1) % maxsize; //rear指针往后移一位;
que[rear] = root; //根节点入队;
while(front != rear)
{
front = (front+1)%maxsize;
p = que[front]; //队头节点出队
Visit(p); //访问队头节点
if(p->lchild != NULL) //如果左子树不空,则左子树根节点入队
{
rear = (rear+1) % maxsize;
que[rear] = p->lchild;
}
if(p->rchild != NULL) //如果右子树不空,则右子树根节点入队
{
rear = (rear+1) % maxsize;
que[rear] = p->rchild;
}
}
}
]
下面是关于C++代码的扩展(考研初试用不上,因为不能用STL库):
void level(node* root)
{
if(root == NULL) return{};
vector<vector<int>> ans;
queue<node*> q;
q.push(root);
while(!q.empty())
{
vector<int> BFS;
node* now = q.front();
int count = q.size();
while(count--)
{
q.pop();
if(now->lchild != NULL)
q.push(now->lchild);
if(now->rchild != NULL)
q.push(now->rchild);
BFS.push_back(now->data);
}
ans.push_back(BFS);
}
return ans;
}