題目
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) {
if (root == NULL) return 0;
if (root->left == NULL && root->right == NULL) return 1;
if (root->left == NULL) return minDepth(root->right) + 1;
else if (root->right == NULL) return minDepth(root->left) + 1;
else return 1 + min(minDepth(root->left), minDepth(root->right));
}
};
分析
二叉樹的經(jīng)典問(wèn)題之最小深度問(wèn)題就是最短路徑的節(jié)點(diǎn)個(gè)數(shù)剩蟀,還是用深度優(yōu)先搜索DFS來(lái)完成,萬(wàn)能的遞歸切威。