用 C 语言编写 采用二叉链表存储方式构建二叉树,并对其进行先序、中序、后序遍历的递归算法和和非递归算法。
时间: 2024-11-12 11:33:37 浏览: 30
在C语言中,我们可以使用结构体表示节点,然后通过指针连接形成二叉链表来构建二叉树。以下是简单的二叉树节点结构定义:
```c
typedef struct TreeNode {
int val; // 节点值
struct TreeNode* left; // 左子节点
struct TreeNode* right; // 右子节点
} TreeNode;
```
**先序遍历(根-左-右)**的递归实现:
```c
void preorderTraversal(TreeNode* root) {
if (root != NULL) {
printf("%d ", root->val); // 先访问根节点
preorderTraversal(root->left); // 再递归遍历左子树
preorderTraversal(root->right); // 最后遍历右子树
}
}
```
**先序遍历**的非递归实现(利用栈):
```c
void preorderTraversalNonRecursive(TreeNode* root) {
stack<TreeNode*> s;
TreeNode* current = root;
while (current || !s.empty()) {
while (current) {
printf("%d ", current->val);
s.push(current);
current = current->left;
}
current = s.top();
s.pop();
current = current->right;
}
}
```
**中序遍历(左-根-右)**的递归实现:
```c
void inorderTraversal(TreeNode* root) {
if (root != NULL) {
inorderTraversal(root->left); // 遍历左子树
printf("%d ", root->val); // 访问根节点
inorderTraversal(root->right); // 遍历右子树
}
}
```
**中序遍历**的非递归实现(同样用栈):
```c
void inorderTraversalNonRecursive(TreeNode* root) {
stack<TreeNode*> s;
TreeNode* current = root;
while (current || !s.empty()) {
while (current) {
s.push(current);
current = current->left;
}
current = s.top();
s.pop();
printf("%d ", current->val);
current = current->right;
}
}
```
**后序遍历(左-右-根)**的递归实现:
```c
void postorderTraversal(TreeNode* root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->val); // 最后访问根节点
}
}
```
**后序遍历**的非递归实现(需要两个栈):
```c
void postorderTraversalNonRecursive(TreeNode* root) {
stack<TreeNode*> s1, s2;
s2.push(root);
while (!s1.empty() || !s2.empty()) {
while (!s2.empty()) {
TreeNode* node = s2.top();
s2.pop();
if (node->left) s1.push(node->left);
if (node->right) s1.push(node->right);
printf("%d ", node->val);
}
if (!s1.empty()) {
TreeNode* temp = s1.top(); // 保存当前节点
s1.pop();
// 将临时节点移动到栈顶,以便继续处理其右子树
s2.push(temp);
}
}
}
```
阅读全文