题目
解法
跟上一题一样的思路
class Solution {
private $minDepth = 0;
/**
* @param TreeNode $root
* @return Integer
*/
function minDepth($root) {
if (empty($root)) {
return $this->minDepth;
}
$this->depth($root, 0);
return $this->minDepth;
}
function depth($root, $depth) {
if (empty($root->left) && empty($root->right)) {
if (empty($this->minDepth) || $this->minDepth > $depth + 1) {
$this->minDepth = $depth + 1;
}
}
if (!empty($root->left)) {
$this->depth($root->left, $depth + 1);
}
if (!empty($root->right)) {
$this->depth($root->right, $depth + 1);
}
}
}