先序中序后序遍历二叉树的递归算法C语言,编写一个程序,实现二叉树的先序遍历,中序遍历,后序遍历的各种递归和非递归算法,以及层次遍历的算法...
时间: 2023-07-21 11:08:53 浏览: 132
好的,下面是二叉树的递归算法实现以及非递归算法实现:
1. 先序遍历递归算法实现:
```c
void preOrderTraversal(TreeNode* root) {
if (root == NULL)
return;
printf("%d ", root->val);
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
```
2. 中序遍历递归算法实现:
```c
void inOrderTraversal(TreeNode* root) {
if (root == NULL)
return;
inOrderTraversal(root->left);
printf("%d ", root->val);
inOrderTraversal(root->right);
}
```
3. 后序遍历递归算法实现:
```c
void postOrderTraversal(TreeNode* root) {
if (root == NULL)
return;
postOrderTraversal(root->left);
postOrderTraversal(root->right);
printf("%d ", root->val);
}
```
4. 先序遍历非递归算法实现:
```c
void preOrderTraversalNonRecursion(TreeNode* root) {
if (root == NULL)
return;
TreeNode* stack[1000];
int top = -1;
stack[++top] = root;
while (top != -1) {
TreeNode* node = stack[top--];
printf("%d ", node->val);
if (node->right)
stack[++top] = node->right;
if (node->left)
stack[++top] = node->left;
}
}
```
5. 中序遍历非递归算法实现:
```c
void inOrderTraversalNonRecursion(TreeNode* root) {
if (root == NULL)
return;
TreeNode* stack[1000];
int top = -1;
TreeNode* node = root;
while (node != NULL || top != -1) {
while (node != NULL) {
stack[++top] = node;
node = node->left;
}
node = stack[top--];
printf("%d ", node->val);
node = node->right;
}
}
```
6. 后序遍历非递归算法实现:
```c
void postOrderTraversalNonRecursion(TreeNode* root) {
if (root == NULL)
return;
TreeNode* stack1[1000];
TreeNode* stack2[1000];
int top1 = -1, top2 = -1;
stack1[++top1] = root;
while (top1 != -1) {
TreeNode* node = stack1[top1--];
stack2[++top2] = node;
if (node->left)
stack1[++top1] = node->left;
if (node->right)
stack1[++top1] = node->right;
}
while (top2 != -1) {
TreeNode* node = stack2[top2--];
printf("%d ", node->val);
}
}
```
7. 层次遍历算法实现:
```c
void levelOrderTraversal(TreeNode* root) {
if (root == NULL)
return;
TreeNode* queue[1000];
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
TreeNode* node = queue[front++];
printf("%d ", node->val);
if (node->left)
queue[rear++] = node->left;
if (node->right)
queue[rear++] = node->right;
}
}
```
注意:以上代码中的 TreeNode 结构体可以根据具体情况自行定义。
阅读全文