用c语言建立以左右孩子链接结构表示的二叉树,实现二叉树的先序、中序、后序的递归和非递归方式遍历,分层遍历、统计树的高度。
时间: 2024-02-13 07:07:02 浏览: 58
二叉树的几种操作,包括递归先序建立二叉树、先序遍历、中序遍历、后序遍历、非递归的各种遍历
好的,我可以为您解答这个问题。
首先,我们需要定义一个二叉树的结构体,包含左右孩子指针和节点值。代码如下:
```c
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
```
接下来,我们来实现二叉树的创建函数,以先序遍历的方式输入节点的值,当遇到空节点时返回 NULL。代码如下:
```c
TreeNode* createTree() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = val;
root->left = createTree();
root->right = createTree();
return root;
}
```
接下来,我们来实现二叉树的先序、中序、后序遍历的递归方式。代码如下:
```c
void preorder(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorder(root->left);
preorder(root->right);
}
void inorder(TreeNode* root) {
if (root == NULL) {
return;
}
inorder(root->left);
printf("%d ", root->val);
inorder(root->right);
}
void postorder(TreeNode* root) {
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
printf("%d ", root->val);
}
```
接下来,我们来实现二叉树的先序、中序、后序遍历的非递归方式。需要借助栈来实现。代码如下:
```c
void preorderNonRecursive(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* stack[100];
int top = -1;
stack[++top] = root;
while (top >= 0) {
TreeNode* p = stack[top--];
printf("%d ", p->val);
if (p->right != NULL) {
stack[++top] = p->right;
}
if (p->left != NULL) {
stack[++top] = p->left;
}
}
}
void inorderNonRecursive(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* stack[100];
int top = -1;
TreeNode* p = root;
while (p != NULL || top >= 0) {
while (p != NULL) {
stack[++top] = p;
p = p->left;
}
p = stack[top--];
printf("%d ", p->val);
p = p->right;
}
}
void postorderNonRecursive(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* stack[100];
int top = -1;
TreeNode* p = root;
TreeNode* lastVisited = NULL;
while (p != NULL || top >= 0) {
while (p != NULL) {
stack[++top] = p;
p = p->left;
}
p = stack[top];
if (p->right == NULL || p->right == lastVisited) {
printf("%d ", p->val);
top--;
lastVisited = p;
p = NULL;
} else {
p = p->right;
}
}
}
```
接下来,我们来实现二叉树的层次遍历,需要借助队列来实现。代码如下:
```c
void levelorder(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* queue[100];
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
TreeNode* p = queue[front++];
printf("%d ", p->val);
if (p->left != NULL) {
queue[rear++] = p->left;
}
if (p->right != NULL) {
queue[rear++] = p->right;
}
}
}
```
最后,我们来实现统计二叉树的高度。代码如下:
```c
int getHeight(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
```
这样,我们就完成了用 C 语言建立以左右孩子链接结构表示的二叉树,并实现了二叉树的先序、中序、后序的递归和非递归方式遍历,分层遍历、统计树的高度。
阅读全文