求二叉树中求结点总数和二叉树叶子结点的代码
时间: 2023-11-18 09:05:22 浏览: 58
下面是二叉树求结点总数和叶子结点数量的代码实现(假设二叉树的节点结构体为Node):
求结点总数:
```
int countNodes(Node* root) {
if (root == nullptr) {
return 0;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
```
求叶子结点数量:
```
int countLeaves(Node* root) {
if (root == nullptr) {
return 0;
}
if (root->left == nullptr && root->right == nullptr) {
return 1;
}
return countLeaves(root->left) + countLeaves(root->right);
}
```
注意,这里的叶子结点指的是没有左右子节点的节点。如果定义叶子结点为没有任何儿子节点的节点,则需要修改判断条件。
相关问题
求二叉树中求结点总数和二叉树叶子结点的算法的代码
下面是二叉树求结点总数和叶子结点数量的算法实现(假设二叉树的节点结构体为Node):
求结点总数:
```
int countNodes(Node* root) {
stack<Node*> s;
int count = 0;
if (root != nullptr) {
s.push(root);
}
while (!s.empty()) {
Node* node = s.top();
s.pop();
count++;
if (node->right != nullptr) {
s.push(node->right);
}
if (node->left != nullptr) {
s.push(node->left);
}
}
return count;
}
```
求叶子结点数量:
```
int countLeaves(Node* root) {
stack<Node*> s;
int count = 0;
if (root != nullptr) {
s.push(root);
}
while (!s.empty()) {
Node* node = s.top();
s.pop();
if (node->right != nullptr) {
s.push(node->right);
}
if (node->left != nullptr) {
s.push(node->left);
}
if (node->left == nullptr && node->right == nullptr) {
count++;
}
}
return count;
}
```
注意,这里的叶子结点指的是没有左右子节点的节点。如果定义叶子结点为没有任何儿子节点的节点,则需要修改判断条件。
代码实现设计求一棵二叉树中结点总数的算法
二叉树结点的总数可以通过遍历二叉树来实现。具体的算法如下:
1. 如果二叉树为空,则结点总数为0.
2. 如果二叉树非空,则结点总数为1(根结点)+ 左子树的结点总数 + 右子树的结点总数。
具体的实现代码如下:
```
int countNodes(TreeNode* root) {
if (root == NULL) {
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}
```
其中,`countNodes`函数接收一个二叉树的根结点指针,返回二叉树的结点总数。如果根节点为空则返回0,否则返回1加上左子树的结点总数和右子树的结点总数。