1、先序遍歷
void preorder(int root) {
if (root == -1) {
return;
}
printf("%d", Node[root]);
preorder(Node[root].lchid);
preorder(Noder[root].rchild);
}
2专钉、中序遍歷
void inorder(int root) {
if (root == -1) {
return;
}
inorder(Node[root].lchid);
printf("%d", Node[root]);
inorder(Noder[root].rchild);
}
3、后序遍歷
void postorder(int root) {
if (root == -1) {
return;
}
postorder(Node[root].lchid);
postorder(Noder[root].rchild);
printf("%d", Node[root]);
}
4累铅、層次遍歷
void layerorder(int root) {
queue<int> q; //此處隊列存放節(jié)點下標
q.push(root); //將根節(jié)點入隊
while (!q.empty()) {
int now = q.front(); //取出隊首元素
q.pop();
printf("%d ", Node[now].data); //訪問隊首元素
if (Node[now].lchild != -1) {
q.push(Node[now].lchild);
}if (Node[node].rchild != -1) {
q.push(Node[now].rchild);
}
}
}