// The tree is in the "static (ie array) implementation" and "pointer implementation" modes respectively ----------------------------- ---------------------------- // Basic operation (define node/build tree/check/change/insert/traverse/rebuild): // Pointer implementation of binary tree: // Definition of tree node struct node { int data; node* l; node* r; }; node* root = NULL; // create new node node* newNode(int v) { node * Node = new node; Node->data = v; Node->l = Node->r = NULL; return Node; } // Find and modify nodes void search(node* root, int x, int newdata) { if(root == NULL) return; if(root->data == x) root->data = newdata; search(root->l, x, newdata); search(root->r, x, newdata); } // insert new node void insert(node* &node, int x) { //Note the reference if(root == NULL) { root = newNode(x); return; } if(/*By the nature of the binary tree, x should be inserted in the left subtree*/) { insert(root->l, x); } else { insert(root->r, x); } } // create a new binary tree node* create(int data[], int n) { node* root = NULL; for(int i=0; i<n; i++) { insert(root, data[i]); } return root; } // The traversal and reconstruction of the binary tree is slightly... // Static (ie array) implementation of binary tree: // define nodes (array) struct node{ int data; int l; int r; } Node [MAXN]; // generate node int index = 0; int newNode(int x) { Node[index].data = v; //Only the pointer method is used " -> " Node[index].l = Node[index].r = -1; return index++; // return the index in the array } // Find and modify nodes void search(int root, int x, int newdata) { if(root == -1) return; if(Node[root].data == x) { Node[root],data = newdata; return; } search(Node[root].l, x, newdata); search(Node[root].r, x, newdata); } // insert void insert(int &root, int x) { //Note the reference if(root == -1) { root = newdata(x); return; } if(/*By the nature of the binary tree, x should be inserted in the left subtree*/) { insert(Node[root].l, x); } else { insert(Node[root].r, x); } } // Static writing of tree: // tree definition struct node { int data; vector<int> child; //Variable-length array //int child[maxn]; //Store the subscripts of all child nodes } Node [MAXN];
The basic operations of tree in "static (ie array) implementation" and "pointer implementation" respectively
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=324645534&siteId=291194637
Recommended
Ranking