题解 | #二叉树的最小深度#
二叉树的最小深度
http://www.nowcoder.com/practice/e08819cfdeb34985a8de9c4e6562e724
树的问题使用递归,注意叶子节点的定义是其左右子均为空,此时将其深度加入结果数组,最后取最小深度:
class Solution {
public:
vector<int> res;
int run(TreeNode* root) {
if(root==nullptr)
return 0;
dfs(root, 1);
return *min_element(res.begin(), res.end());
}
void dfs(TreeNode* root, int depth){
if(root->left==nullptr && root->right==nullptr){
res.emplace_back(depth);
return ;
}
if(root->left)
dfs(root->left, depth+1);
if(root->right)
dfs(root->right, depth+1);
return ;
}
};