二叉树采用链接存储方式存储,分别编写一个二叉树先序遍历的递归算法和非递归算法,用c语言实现
时间: 2023-05-11 21:04:46 浏览: 188
好的,以下是二叉树先序遍历的递归算法和非递归算法的C语言实现:
递归算法:
```c
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void preorderTraversal(struct TreeNode* root){
if(root == NULL){
return;
}
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
```
非递归算法:
```c
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void preorderTraversal(struct TreeNode* root){
if(root == NULL){
return;
}
struct TreeNode* stack[1000];
int top = -1;
stack[++top] = root;
while(top >= 0){
struct TreeNode* node = stack[top--];
printf("%d ", node->val);
if(node->right != NULL){
stack[++top] = node->right;
}
if(node->left != NULL){
stack[++top] = node->left;
}
}
}
```
希望这个回答能够帮到你!
阅读全文