通过queue 队列来进行 insert 操作,判断 tree 的各个节点是否存在 left 和 right 为NULL的情况,如果有就将 新的 叶子插入。这里要循环遍历树,通过 queue 来进行判断,如果root(根),不为空,将其enqueue(),然后看代码吧
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 struct tree 5 { 6 int data; 7 struct tree * left; 8 struct tree * right; 9 }; 10 struct queue 11 { 12 int rear, front, size; 13 unsigned capacity; 14 struct tree ** array; 15 }; 16 struct queue * creatQueue(int capacity) 17 { 18 struct queue * q = (struct queue *)malloc(sizeof(struct queue)); 19 q->capacity = capacity; 20 q->rear = capacity-1; 21 q->front = 0; 22 q->size = 0; 23 q->array = (struct tree *)malloc(capacity * sizeof(struct tree)); 24 25 return q; 26 } 27 int isFull(struct queue * q) 28 { 29 return q->size == q->capacity ? 1 : 0; 30 } 31 int isEmpty(struct queue * q) 32 { 33 return 0 == q->size ? 1 : 0; 34 } 35 void enQueue(struct queue * q, struct tree * node) 36 { 37 if(isFull(q)) 38 { 39 printf(" Full"); 40 return ; 41 } 42 else 43 { 44 q->rear = (q->rear+1) % q->capacity; 45 q->array[q->rear] = node; 46 q->size += 1; 47 } 48 } 49 struct tree * deQueue(struct queue * q) 50 { 51 struct tree * node; 52 53 if(isEmpty(q)) 54 { 55 node = NULL; 56 return node; 57 } 58 else 59 { 60 node = q->array[q->front]; 61 q->front = (q->front+1) % q->capacity; 62 q->size -= 1; 63 return node; 64 } 65 } 66 struct tree * newNode(int data) 67 { 68 struct tree * root = (struct tree *)malloc(sizeof(struct tree)); 69 root->data = data; 70 root->left = NULL; 71 root->right = NULL; 72 73 return root; 74 } 75 void printLevelOrder(struct tree * root) 76 { 77 struct queue * q = creatQueue(20); 78 struct tree * temp = root; 79 80 while(NULL != temp) 81 { 82 printf("%d ", temp->data); 83 84 if(temp->left) 85 { 86 enQueue(q, temp->left); 87 } 88 if(temp->right) 89 { 90 enQueue(q, temp->right); 91 } 92 93 temp = deQueue(q); 94 } 95 } 96 void insertTree(struct tree * root, int data) 97 { 98 struct queue * q = creatQueue(20); 99 enQueue(q, root); 100 while(1) 101 { 102 struct tree * temp = deQueue(q); 103 104 if(NULL == temp->left) 105 { 106 temp->left = newNode(data); 107 break; 108 } 109 else 110 { 111 enQueue(q, temp->left); 112 } 113 if(NULL == temp->right) 114 { 115 temp->right = newNode(data); 116 break; 117 } 118 else 119 { 120 enQueue(q, temp->right); 121 } 122 } 123 } 124 int main(void) 125 { 126 struct tree * root = newNode(1); 127 root->left = newNode(2); 128 root->right = newNode(3); 129 root->right->left = newNode(4); 130 root->right->right = newNode(5); 131 132 printLevelOrder(root); 133 insertTree(root, 6); 134 printf(" "); 135 printLevelOrder(root); 136 return 0; 137 }