求二叉树最小深度的C++代码
时间: 2024-05-08 09:15:34 浏览: 17
下面是求二叉树最小深度的C代码:
```
#include <stdio.h>
#include <stdlib.h>
// 二叉树节点结构体
struct Node {
int val;
struct Node* left;
struct Node* right;
};
// 创建节点
struct Node* createNode(int val)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->val = val;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// 递归计算二叉树最小深度
int minDepth(struct Node* root)
{
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
}
int leftDepth = (root->left != NULL) ? minDepth(root->left) : INT_MAX;
int rightDepth = (root->right != NULL) ? minDepth(root->right) : INT_MAX;
return 1 + (leftDepth < rightDepth ? leftDepth : rightDepth);
}
int main()
{
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
printf("The minimum depth of the binary tree is %d", minDepth(root));
return 0;
}
```
该代码通过递归方式计算二叉树的最小深度。首先判断当前节点是否为空,如果为空则返回0,否则如果当前节点为叶子节点,则返回1。否则分别计算左子树和右子树的最小深度,然后返回1加上左右子树中较小的深度。