The basic operation of the tree - comes with C ++ implementation code

Definition 1

1.1 storage structure to achieve

const int MAXN = 20;
typedef int ElemType;
struct node
{
    ElemType data;//数据域
    vector<int> child;//指针域,存放所有子结点结点
    int layer;//记录层号
}Node[MAXN];//结点数组

2 Basic Operation

New node 2.1

//新建结点
int Index = 0;
int newNode(int v){
    Node[Index].data = v;
    Node[Index].child.clear();
    return Index++;//返回结点下标,并令index递增
} 

2.2 First Traversal

//先序遍历
void preorder(int root){
    printf("%d\n", Node[root].data);
    for (int i = 0; i < Node[root].child.size(); ++i)
    {
        preorder(Node[root].child[i]);
    }
}

2.3 traversal sequence

2.3.1 traversal sequence

//层序遍历
void layerorder(int root){
    queue<int> q;
    q.push(root);
    while(!q.empty()){
        int now = q.front();
        q.pop();

        printf("%d\n", Node[now].data);

        for (int i = 0; i < Node[now].child.size(); ++i)
        {
            q.push(Node[now].child[i]);
        }
    }
}

2.3.2 traversal sequence (with statistics layers)

//层序遍历2
void layerorder(int root){
    queue<int> q;
    Node[root].layer = 0;
    q.push(root);
    while(!q.empty()){
        int now = q.front();
        q.pop();

        printf("%d\n", Node[now].data);

        for (int i = 0; i < Node[now].child.size(); ++i)
        {
            int child = Node[now].child[i];
            Node[child].layer = Node[now].layer + 1;
            q.push(child);
        }
    }
}
Published 321 original articles · won praise 51 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_33375598/article/details/104131409