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);
        }
    }
}
posted @ 2021-06-02 18:09  吴丹阳-V  阅读(33)  评论(0编辑  收藏  举报