树的先根遍历
树的先根遍历,即总是先访问根节点,再去访问左右子树,是一个递归访问的概念,因为对根结点的子树而言,同样可以划分为根节点和若干子树,这种遍历方式称为树的先根遍历。
代码如下:(简单框架)
void preorder(int root){
printf("%d",Node[root].data);//访问当前结点
for(int i=0;i<Node[root].child.size();i++){
preorder(Node[root].child[i]);//递归访问结点root的所有子结点
}
}
树的层次遍历
树的层次遍历与二叉树的层次遍历的思路是一样的,即总是从树根开始,一层一层的向下进行访问。
树的层次遍历的实现方法和二叉树的类似,一般是使用队列来存放结点再数组中的下标,每次取出队首元素来访问,将其子结点加入队列,直到队列为空,可以在二叉树的层次遍历的基础上来写出树的层次遍历。
代码如下:
void LayerOrder(int root){
queue<int>q;
q.push(root);
while(!q.empty()){
int front=q.front();//取出队首元素
printf("%d ",Node[front].data);//访问当前结点的数据域
q.pop();
for(int i=0;i<Node[front].child.size();i++){
q.push(Node[front].child[i]);
}
}
}
同样的,如果需要对结点的层号进行求解,只需要在结构体node的定义中增加变量来记录结点的层号
struct node{
int layer;//记录层号
int data;
vector<int>child;
};
于是树的层次遍历就可以写成下面这样
void LayerOrder(int root){
queue<int>q;
q.push(root);
Node[root].layer=0;
while(!q.empty()){
int front=q.front();//取出队首元素
printf("%d ",Node[front].data);//访问当前结点的数据域
q.pop();
for(int i=0;i<Node[front].child.size();i++){
int child=Node[front].child[i];
Node[child].layer=Node[front].layer+1;
q.push(Node[front].child[i]);
}
}
}