Leetcode:Minimum Depth of Binary Tree
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.
分析:此题跟maximum depth of binary tree相似,但要注意的是minimum depth的定义,如果根节点的某个孩子为null,我们将不考虑该孩子的高度因为minimum depth定义是根到叶子节点的最短路径上的节点数。代码如下:
class Solution { public: int minDepth(TreeNode *root) { if(root == NULL) return 0; int left_depth = minDepth(root->left); int right_depth = minDepth(root->right); if(left_depth == 0) return right_depth + 1; if(right_depth == 0) return left_depth + 1; return min(right_depth, left_depth) + 1; } };