Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
递归。
考虑5种情况,
1.节点为空
2.节点不为空,且左右儿子节点也不为空
3,右儿子节点为空
4,左儿子节点为空
5,左右儿子都为空
int minDepth(TreeNode *root) {
if (root == NULL)
return 0;
int a=0, b=0;
if (root->left &&root->right){
a = minDepth(root->left) + 1;
b = minDepth(root->right) + 1;
return a < b ? a : b;
}else
if (root->left && root->right==NULL){
return 1 + minDepth(root->left);
}else
if (root->right && root->left==NULL){
return 1 + minDepth(root->right);
}else
if (root->left == NULL && root->right == NULL){
return 1;
}
}

本文介绍如何通过递归算法找到二叉树的最小深度,即从根节点到最近叶子节点的最短路径长度。
376

被折叠的 条评论
为什么被折叠?



