Problem-solving ideas:
(1) Use recursion
(2) Note that the minimum height of a node is the minimum height of the left and right subtrees + 1
(3) Note that if the height of one of the subtrees is 0, then the height of the other subtree + 1 is the minimum height of the node
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if (root) return dfs(root);
else return 0;
}
private:
int dfs(TreeNode* node) {
int l = node->left ? dfs(node->left) : 0;
int r = node->right ? dfs(node->right) : 0;
if (l==0) return r+1;
if (r==0) return l+1;
else return min(l,r)+1;
}
};