#include <stdio.h> #include <stdlib.h> // binary list // typedef struct BitLink { // int data; // struct BitLink * leftChild; // left pointer // struct BitLink * rightChild; // Right pointer //} bitlink; // Build a tree with a binary linked list storage typedef struct BitTree { int data; struct BitTree * LChild; // left subtree struct BitTree * RChild; // right subtree } bittree; bittree * createBitTree ( bittree * BT) { BT = (bittree *) malloc (sizeof (bittree)); BT-> data = 1; BT-> LChild = (bittree *) malloc (sizeof (bittree)); BT-> RChild = (bittree *) malloc (sizeof (bittree)); BT-> LChild-> data = 2; BT-> LChild-> RChild = NULL; BT-> RChild-> data = 3; BT-> RChild-> LChild = NULL; BT-> RChild-> RChild = NULL; BT-> LChild-> LChild = (bittree *) malloc (sizeof (bittree)); BT-> LChild-> LChild-> data = 4; BT-> LChild-> LChild -> LChild = NULL; BT-> LChild-> LChild-> RChild = NULL; return BT; } void main () { bittree * myBT = NULL; myBT = createBitTree (myBT); printf ("The root node of the tree is: % d \ n ", myBT-> data); printf (" The leaf nodes of the tree are:% d,% d \ n ", myBT-> LChild-> LChild-> data, myBT-> RChild-> data); }
Use recursive method to establish:
#include <stdio.h> #include <stdlib.h> // Build a tree with a binary linked list storage (complete binary tree) typedef struct BitTree { int data; struct BitTree * LChild; // left subtree struct BitTree * RChild; / / Right subtree } bittree; // Create binary tree bittree * createBitTree (bittree * BT) { int num = 0; scanf ("% d", & num); if (num! = -1) {// Enter -1 for End BT = (bittree *) malloc (sizeof (bittree)); BT-> data = num; printf ("Enter the left node value of% d:", BT-> data); BT-> LChild = createBitTree (BT -> LChild); printf ("Enter the right node value of% d:", BT-> data); BT-> RChild = createBitTree (BT-> RChild); return BT; } } void main() { bittree* myBT = NULL; myBT = createBitTree (myBT); printf ("The root node of the tree is:% d \ n", myBT-> data); printf ("The left node of the tree's root node is:% d \ n", myBT-> LChild-> data) ; printf ("The right node of the root node of the tree is:% d \ n", myBT-> RChild-> data); }