c++用链表实现根据输入的数据建立一个二叉树,输出树型结构二叉树,输出其前序 中序 和后序遍历的结果,输出树的深度,最大元,最小元
时间: 2024-09-22 15:00:43 浏览: 33
在C++中,我们可以使用链表数据结构来构建二叉搜索树,并通过递归的方式实现前序、中序和后序遍历。首先,我们需要定义一个二叉节点类,包含数据、左指针和右指针:
```cpp
class TreeNode {
public:
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
```
接下来,我们创建一个函数来根据链表元素建立二叉搜索树:
```cpp
TreeNode* buildBST(ListNode* head) {
if (head == nullptr) return nullptr;
TreeNode* root = new TreeNode(head->val);
auto it = head->next;
while (it != nullptr) {
if (it->val < root->val)
root->left = buildBST(it);
else if (it->val > root->val)
root->right = buildBST(it);
it = it->next;
}
return root;
}
```
现在我们可以分别编写前序、中序和后序遍历的递归函数:
```cpp
void preOrder(TreeNode* node) {
if (node == nullptr) return;
std::cout << node->val << " ";
preOrder(node->left);
preOrder(node->right);
}
void inOrder(TreeNode* node) {
if (node == nullptr) return;
inOrder(node->left);
std::cout << node->val << " ";
inOrder(node->right);
}
void postOrder(TreeNode* node) {
if (node == nullptr) return;
postOrder(node->left);
postOrder(node->right);
std::cout << node->val << " ";
}
```
至于输出树的深度、最大值和最小值,可以添加如下的辅助函数:
```cpp
int treeDepth(TreeNode* root) {
if (root == nullptr) return 0;
return 1 + max(treeDepth(root->left), treeDepth(root->right));
}
int findMaxAndMin(TreeNode* node, int& maxVal, int& minVal) {
if (node == nullptr) return -1;
int leftResult = findMaxAndMin(node->left, maxVal, minVal);
int rightResult = findMaxAndMin(node->right, maxVal, minVal);
if (leftResult == -1) {
maxVal = node->val > maxVal ? node->val : maxVal;
minVal = node->val < minVal ? node->val : minVal;
} else {
maxVal = std::max(maxVal, leftResult);
minVal = std::min(minVal, leftResult);
}
if (rightResult == -1) {
maxVal = node->val > maxVal ? node->val : maxVal;
minVal = node->val < minVal ? node->val : minVal;
} else {
maxVal = std::max(maxVal, rightResult);
minVal = std::min(minVal, rightResult);
}
return node->val;
}
```
最后,你可以像下面这样调用上述函数:
```cpp
// 假设head指向已排序的链表头结点
auto root = buildBST(head);
std::cout << "Preorder traversal: ";
preOrder(root);
std::cout << "\nInorder traversal: ";
inOrder(root);
std::cout << "\nPostorder traversal: ";
postOrder(root);
int maxVal, minVal;
findMaxAndMin(root, maxVal, minVal);
std::cout << "\nTree depth: " << treeDepth(root) << "\nMax value: " << maxVal << "\nMin value: " << minVal;
```
阅读全文