题目:
思想:
有题目可知,最小深度的计算方式是从根节点到最近的叶节点的节点的个数。对于一个空节点,其高度自然为0;对于有一个节点为空,一个节点不为空的情况,根据最小深度的定义方式,应该取非空的节点的高度;对于两者均非空,应该取二者中较小者。
代码:
/**
* Definition for a binary tree node.
**/
typedef struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
}*BinaryTree;
class Solution {
public:
void CreateTree(BinaryTree &T)
{
char data;
cin >> data;
if (data == '#')
T = NULL;
else
{
T = new TreeNode(data - '0');
CreateTree(T->left);
CreateTree(T->right);
}
}
int minDepth(TreeNode* root) {
if (root == NULL)
{
return 0;
}
if (root->left == NULL || root->right ==NULL)
{
return max(minDepth(root->left), minDepth(root->right)) + 1;
}
else
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
};