(C/C++) Binary Tree

  1 // Recursive C program for level order traversal of Binary Tree 
  2 #include <stdio.h> 
  3 #include <stdlib.h> 
  4 
  5 struct node
  6 {
  7     int data;
  8     struct node *left;
  9     struct node *right;
 10 };
 11 
 12 struct node* newNode(int data)
 13 {
 14     struct node *node = (struct node*)malloc(sizeof(struct node));
 15     node->data = data;
 16     node->left = NULL;
 17     node->right = NULL;
 18     return node;
 19 }
 20 
 21 int height(struct node* node)
 22 {
 23     if (node == NULL)
 24         return 0;
 25     else
 26     {
 27         int lheight = height(node->left);
 28         int rheight = height(node->right);
 29 
 30         if (lheight > rheight)
 31             return lheight + 1;
 32         else
 33             return rheight + 1;
 34     }
 35 }
 36 
 37 void printGivenLevel(struct node *root, int level)
 38 {
 39     if (root == NULL)
 40         return;
 41     else if (level == 1)
 42         printf("%d ", root->data);
 43     else if (level > 1)
 44     {
 45         printGivenLevel(root->left, level - 1);
 46         printGivenLevel(root->right, level - 1);
 47     }
 48 }
 49 
 50 void printLevelOrder(struct node * root)
 51 {
 52     int h = height(root);
 53     int i;
 54     for (i = 1; i <= h; i++)
 55         printGivenLevel(root, i);
 56 }
 57 
 58 void printPostorder(struct node* node)
 59 {
 60     if (node == NULL)
 61         return;
 62 
 63     // first recur on left subtree 
 64     printPostorder(node->left);
 65 
 66     // then recur on right subtree 
 67     printPostorder(node->right);
 68 
 69     // now deal with the node 
 70     printf("%d ", node->data);
 71 }
 72 
 73 /* Given a binary tree, print its nodes in inorder*/
 74 void printInorder(struct node* node)
 75 {
 76     if (node == NULL)
 77         return;
 78 
 79     /* first recur on left child */
 80     printInorder(node->left);
 81 
 82     /* then print the data of node */
 83     printf("%d ", node->data);
 84 
 85     /* now recur on right child */
 86     printInorder(node->right);
 87 }
 88 
 89 /* Given a binary tree, print its nodes in preorder*/
 90 void printPreorder(struct node* node)
 91 {
 92     if (node == NULL)
 93         return;
 94 
 95     /* first print data of node */
 96     printf("%d ", node->data);
 97 
 98     /* then recur on left sutree */
 99     printPreorder(node->left);
100 
101     /* now recur on right subtree */
102     printPreorder(node->right);
103 }
104 
105 
106 int main(void)
107 {
108     struct node *root = newNode(1);
109     root->left = newNode(2);
110     root->right = newNode(3);
111     root->left->left = newNode(4);
112     root->left->right = newNode(5);
113     printf("Level Order traversal of binary tree is \n");
114     printLevelOrder(root);
115 
116     system("pause");
117     return 0;
118 }

 

posted on 2019-04-18 23:37  OO程式猿  阅读(324)  评论(0)    收藏  举报

导航