用c++建立二叉树链表,并运用先序遍历算法,中序遍历算法,后序遍历算法,求二叉树结点个数,二叉树的深度,二叉树叶子节点数,输出叶子节点
时间: 2024-11-06 21:16:12 浏览: 60
在 C++ 中,我们可以创建一个二叉树结构,其中每个节点包含一个值、左指针和右指针。首先,我们定义一个简单的二叉树节点结构:
```cpp
template <typename T>
struct TreeNode {
T value;
TreeNode* left;
TreeNode* right;
TreeNode(T val) : value(val), left(nullptr), right(nullptr) {}
};
```
接下来,我们分别实现先序、中序和后序遍历算法,以及计算节点总数、深度和叶子节点数的方法:
```cpp
void preOrder(TreeNode<T>* root) {
if (root != nullptr) {
cout << root->value << " ";
preOrder(root->left);
preOrder(root->right);
}
}
void inOrder(TreeNode<T>* root) {
if (root != nullptr) {
inOrder(root->left);
cout << root->value << " ";
inOrder(root->right);
}
}
void postOrder(TreeNode<T>* root) {
if (root != nullptr) {
postOrder(root->left);
postOrder(root->right);
cout << root->value << " ";
}
}
int countNodes(TreeNode<T>* root) {
return (root == nullptr) ? 0 : 1 + countNodes(root->left) + countNodes(root->right);
}
int treeDepth(TreeNode<T>* root) {
if (root == nullptr) return 0;
int leftDepth = treeDepth(root->left);
int rightDepth = treeDepth(root->right);
return max(leftDepth, rightDepth) + 1;
}
int leafCount(TreeNode<T>* root) {
if (root == nullptr || (root->left == nullptr && root->right == nullptr)) return (root == nullptr) ? 0 : 1;
return leafCount(root->left) + leafCount(root->right);
}
```
为了输出叶子节点,你可以像下面这样调用 `leafCount` 函数:
```cpp
int leafNodes = leafCount(root);
cout << "叶节点数: " << leafNodes << endl;
```
阅读全文
相关推荐
















