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.
题目要找出根节点到叶子节点的最小深度的节点数。递归分治如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (root == NULL)
return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
if (left == 0) // 左孩子为NULL
return right + 1;
if (right == 0) // 右孩子为NULL
return left + 1;
return left < right ? left +1: right+1;
}
};