c++编程实现:求二叉树的高度和叶子结点个数
时间: 2023-12-17 10:11:16 浏览: 27
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int getHeight(TreeNode* root) {
if (root == NULL) return 0;
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return max(leftHeight, rightHeight) + 1;
}
int getLeafCount(TreeNode* root) {
if (root == NULL) return 0;
if (root->left == NULL && root->right == NULL) return 1;
return getLeafCount(root->left) + getLeafCount(root->right);
}
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
int height = getHeight(root);
int leafCount = getLeafCount(root);
cout << "The height of the binary tree is: " << height << endl;
cout << "The number of leaf nodes in the binary tree is: " << leafCount << endl;
return 0;
}