用C语言实现非递归的方法实现对给定二叉树的先序和层序遍历算法。
时间: 2024-05-10 14:21:34 浏览: 108
先序遍历非递归实现:
```c
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
Stack stack;
stackInit(&stack);
stackPush(&stack, root);
while (!stackIsEmpty(&stack)) {
TreeNode* node = stackTop(&stack);
stackPop(&stack);
printf("%d ", node->val);
if (node->right != NULL) {
stackPush(&stack, node->right);
}
if (node->left != NULL) {
stackPush(&stack, node->left);
}
}
}
```
层序遍历非递归实现:
```c
void levelOrderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
Queue queue;
queueInit(&queue);
queuePush(&queue, root);
while (!queueIsEmpty(&queue)) {
int levelSize = queueSize(&queue);
for (int i = 0; i < levelSize; i++) {
TreeNode* node = queueFront(&queue);
queuePop(&queue);
printf("%d ", node->val);
if (node->left != NULL) {
queuePush(&queue, node->left);
}
if (node->right != NULL) {
queuePush(&queue, node->right);
}
}
}
}
```
阅读全文