Notes - Static Binary Link List

Static Binary Link List

Use arrays instead of pointers to complete all binary tree operations

The left and right pointer fields of the nodes are replaced by int to represent the subscripts of the root nodes of the left and right subtrees in the array.
Change pointer operation to array subscript access

struct node{
    typename data;
    int lchild;   //Pointer field pointing to left subtree
    int rchild;   //Pointer field pointing to right subtree
}Node[maxn];
int index = 0;

int newNode(int v){  //Assign a node in the Node array to a new node with index as its subscript
    Node[index].data = v;
    Node[index].lchild = -1;
    Node[index].rchild = -1;  //- 1 and maxn denote null because the array range is 0-maxn
    return index++;
}
Find (root is the subscript of the root node in the array)
void search(int root, int x, int newdata){
    if(root == -1){
        return;  //Recursive boundary of empty tree dead alley
    }
    if(Node[root].data == x){
        Node[root].data = newdata;
    }
    search(Node[root].lchild, x, newdata);  //Recursion to the left subtree
    search(Node[root].rchild, x, newdata);  //Recursion to the right subtree
}
insert
void insert(int &root, int x){  // root preceded by & quoted by ____________
    if(root == -1){  // Empty Tree Finding Failure Inserts Recursive Boundary
        root = newNode(x);
        return;
    }
    if(){
        insert(Node[root].lchild, x);
    }else{
        insert(Node[root].rchild, x);
    }
}

establish

int Create(int data[], int n){
    int root = -1;
    for(int i = 0; i < n; i++){
        insert(root, data[i]);
    }
    return root;
}
Preorder traversal
void preorder(int root){
    if(root == -1){
        return;
    }
    printf("%d\n", Node[root].data);
    preorder(Node[root].lchild);
    preorder(Node[root].rchild);
}
Sequential traversal
void inorder(int root){
    if(root == -1){
        return;
    }
    inorder(Node[root].lchild);
    printf("%d\n", Node[root].data);
    inorder(Node[root].rchild);
}
Post order traversal
void postorder(int root){
    if(root == -1){
        return;
    }
    postorder(Node[root].lchild);
    postorder(Node[root].rchild);
    printf("%d\n", Node[root].data);
}
level traversal
void LayerOrder(int root){
    queue<int> q;  //Storage Node Subscription
    q.push(root);
    while(!q.empty()){
        int now = q.front();  //Remove the team leader element
        q.pop();
        printf("%d ", Node[now].data);
        if(Node[now].lchild != -1) q.push(Node[now].lchild);
        if(Node[now].rchild != -1) q.push(Node[now].rchild);
    }
}

Posted by gregchet on Thu, 03 Oct 2019 02:27:09 -0700