Suppose a ternary group (n,p, L/R) of each node is entered from left to right, from top to bottom by hierarchy. where n is the element of this node, p is its parent node, L indicates that n is the left child of P, r indicates that n is the right child of P. Try to write a two-yuan tree of the left and right chain representation algorithm, and the implementation of the first root, act, after the root and sequence traversal algorithm.
#include <stdio.h> #include <stdlib.h> #define MAX typedef int ElementType;
struct Node {struct node *lchild;
struct node *rchild;
ElementType data;
};
typedef node *btree;
BTREE Createtree ();
int IsEmpty (BTREE root);
void Visit (int n);
void Inorder (BTREE root);
void Postorder (BTREE root);
void preorder (BTREE root);
int main () {struct node *root;
BTREE Tree[max];
root = Createtree ();
printf ("Root traversal: \ n");
Inorder (root);
printf ("\ n");
printf ("First root traversal: \ n");
Preorder (root);
printf ("\ n");
printf ("Post-root traversal: \ n");
Postorder (root);
printf ("\ n");
return 0;
} BTREE Createtree () {BTREE root;
BTREE NewNode;
BTREE Tree[max];
ElementType data;
int number;//record node position int i;
int j=1;
Char LR;
root = new struct node;//new root node root->lchild = NULL;
Root->rchild = NULL;
printf ("Input root node data: \ n");
scanf ("%d", &data);
Root->data = data;
Number = 0;
Tree[0] = root;
printf ("Input triples (node data, node designator (starting from 0), L/R), to enter 0,0,0 as end \ n"); scanf ("%d,%d,%c",&DATA,&I,&LR); while (data!=0 | | i!=0 | |
LR! = ' 0 ')//To enter 0,0,0 as end {newNode = new struct node;
Newnode->data = data;
number++;
Tree[number] = NewNode;
if (LR = = ' L ') {tree[i]->lchild = NewNode;
} if (LR = = ' R ') {tree[i]->rchild = NewNode;
} newnode->lchild = Newnode->rchild = null;//Initialize printf ("Input triples (node data, node designator, L/R) to enter 0,0,0 as end \ n");
scanf ("%d,%d,%c", &DATA,&I,&LR);
} root = Tree[0];
printf ("Sequence traversal: \ n");
for (i=0;i<number+1;i++) printf ("%d", tree[i]->data);
printf ("\ n");
return root;
} int IsEmpty (BTREE root) {if (root = NULL) {return 1;
} else return 0;
} void Visit (ElementType data) {printf ("%d", data);
void Inorder (BTREE root)//in root traversal {if (IsEmpty (root) = = 0) {inorder (root->lchild);
Visit (Root->data);
Inorder (Root->rchild);
}} void preorder (BTREE root)//first root traversal {if (IsEmpty (root) = = 0) { Visit (Root->data);
Preorder (Root->lchild);
Preorder (Root->rchild);
}} void Postorder (BTREE root)//after root traversal {if (IsEmpty (root) = = 0) {postorder (root->lchild);
Postorder (Root->rchild);
Visit (Root->data);
}
}
Above for your reference