以二叉链表表示二叉树,建立一个二叉树的完整代码
时间: 2023-11-18 07:09:53 浏览: 32
以下是建立二叉树的完整代码:
```
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
TreeNode* createTree(TreeNode* root, int arr[], int i, int n) {
if (i < n) {
TreeNode* temp = new TreeNode(arr[i]);
root = temp;
root->left = createTree(root->left, arr, 2 * i + 1, n);
root->right = createTree(root->right, arr, 2 * i + 2, n);
}
return root;
}
void inorderTraversal(TreeNode* root) {
if (root != nullptr) {
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
}
int main() {
int n;
cout << "Enter the number of nodes in the binary tree: ";
cin >> n;
int arr[n];
cout << "Enter the values of each node in the binary tree:\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
TreeNode* root = createTree(root, arr, 0, n);
cout << "Inorder traversal of the binary tree:\n";
inorderTraversal(root);
return 0;
}
```
该代码使用二叉链表表示二叉树,采用递归的方式建立二叉树,并对二叉树进行中序遍历。输入为二叉树的节点数以及每个节点的值,输出为中序遍历结果。