二叉树 统计特定元素的个数 代码
时间: 2023-05-17 08:05:44 浏览: 76
以下是一个统计二叉树中特定元素个数的代码示例:
```
int count(TreeNode* root, int target) {
if (!root) {
return 0;
}
int cnt = (root->val == target) ? 1 : 0;
cnt += count(root->left, target);
cnt += count(root->right, target);
return cnt;
}
```
其中,`root` 表示二叉树的根节点,`target` 表示需要统计的特定元素。函数返回值为特定元素在二叉树中出现的次数。
注意:这只是一个示例代码,实际应用中可能需要根据具体情况进行修改和优化。
相关问题
c语言统计二叉树中结点的个数
统计二叉树中结点的个数可以使用递归的方法进行求解,具体实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结点结构体
typedef struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 创建二叉树
TreeNode* createBinaryTree() {
int data;
scanf("%d", &data);
if (data == -1) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = data;
root->left = createBinaryTree();
root->right = createBinaryTree();
return root;
}
// 统计二叉树中结点的个数
int countNodes(TreeNode* root) {
if (root == NULL) {
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}
int main() {
printf("请输入二叉树的结点(-1表示空结点):\n");
TreeNode* root = createBinaryTree();
printf("二叉树中结点的个数为:%d\n", countNodes(root));
return 0;
}
```
输入样例:
```
请输入二叉树的结点(-1表示空结点):
1 2 4 -1 -1 5 -1 -1 3 -1 -1
```
输出样例:
```
二叉树中结点的个数为:5
```
建立一个完全二叉树,能够统计二叉树的叶子结点的个数,求二叉树的深度的python代码
以下是Python代码实现:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
left_depth = self.get_depth(root.left)
right_depth = self.get_depth(root.right)
if left_depth == right_depth:
return 2 ** left_depth + self.countNodes(root.right)
else:
return 2 ** right_depth + self.countNodes(root.left)
def get_depth(self, root: TreeNode) -> int:
if not root:
return 0
depth = 0
while root:
depth += 1
root = root.left
return depth
```
对于一个完全二叉树,可以利用完全二叉树的性质来统计叶子节点的个数和深度。可以通过递归的方式来实现,如果左子树和右子树的深度相同,那么左子树一定是满二叉树,可以通过公式 $2^h-1$ 来计算左子树的节点数,同时递归计算右子树的节点数;如果左子树的深度比右子树深度大一,那么右子树一定是满二叉树,同样可以通过公式 $2^h-1$ 来计算右子树的节点数,同时递归计算左子树的节点数。对于深度的计算,可以从根节点一直往左子树遍历,得到深度。