leetcode-111. 二叉树的最小深度

题目

111. 二叉树的最小深度

解法

跟上一题一样的思路

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);
        }
    }
}
原文地址:https://www.cnblogs.com/wudanyang/p/14842337.html