请用c++实现二叉树的建立,二叉树的前序算法(递归和非递归两种方法)
时间: 2024-03-01 18:35:20 浏览: 63
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 递归建立二叉树
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;
}
// 非递归建立二叉树
TreeNode* createTreeIter() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = val;
TreeNode** stack = (TreeNode**)malloc(sizeof(TreeNode*) * 1000);
int top = -1;
stack[++top] = root;
while (top >= 0) {
TreeNode* node = stack[top--];
scanf("%d", &val);
if (val == -1) {
node->left = NULL;
} else {
node->left = (TreeNode*)malloc(sizeof(TreeNode));
node->left->val = val;
stack[++top] = node->left;
}
scanf("%d", &val);
if (val == -1) {
node->right = NULL;
} else {
node->right = (TreeNode*)malloc(sizeof(TreeNode));
node->right->val = val;
stack[++top] = node->right;
}
}
free(stack);
return root;
}
// 递归前序遍历
void preOrder(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preOrder(root->left);
preOrder(root->right);
}
// 非递归前序遍历
void preOrderIter(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode** stack = (TreeNode**)malloc(sizeof(TreeNode*) * 1000);
int top = -1;
stack[++top] = root;
while (top >= 0) {
TreeNode* node = stack[top--];
printf("%d ", node->val);
if (node->right != NULL) {
stack[++top] = node->right;
}
if (node->left != NULL) {
stack[++top] = node->left;
}
}
free(stack);
}
int main() {
printf("请输入二叉树,-1表示空节点:\n");
TreeNode* root = createTreeIter();
printf("递归前序遍历结果:\n");
preOrder(root);
printf("\n非递归前序遍历结果:\n");
preOrderIter(root);
return 0;
}
阅读全文