使用c语言重新编写以上三个代码
时间: 2023-08-02 07:08:15 浏览: 48
好的,以下是使用 C 语言重新实现的三个算法:
1. 统计二叉树叶节点个数的算法:
```c
int count_leaf_nodes(TreeNode* root) {
if (!root) {
return 0;
}
if (!root->left && !root->right) {
return 1;
}
return count_leaf_nodes(root->left) + count_leaf_nodes(root->right);
}
```
2. 判别两棵树是否相等的算法:
```c
bool is_same_tree(TreeNode* p, TreeNode* q) {
if (!p && !q) {
return true;
}
if (!p || !q) {
return false;
}
if (p->val != q->val) {
return false;
}
return is_same_tree(p->left, q->left) && is_same_tree(p->right, q->right);
}
```
3. 输出二叉树中从每个叶子结点到根结点的路径的算法:
```c
void print_paths_helper(TreeNode* node, int* path, int len) {
if (!node) {
return;
}
path[len++] = node->val;
if (!node->left && !node->right) {
for (int i = len - 1; i >= 0; i--) {
printf("%d ", path[i]);
}
printf("\n");
} else {
print_paths_helper(node->left, path, len);
print_paths_helper(node->right, path, len);
}
}
void print_paths(TreeNode* root) {
if (!root) {
return;
}
int path[1000];
print_paths_helper(root, path, 0);
}
```
希望这些代码能够帮到你!