111. Minimum Depth of Binary Tree

BFS 找最小層數

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($val = 0, $left = null, $right = null) {
 *         $this->val = $val;
 *         $this->left = $left;
 *         $this->right = $right;
 *     }
 * }
 */
class Solution {

    /**
     * @param TreeNode $root
     * @return Integer
     */
    function minDepth($root) {
        if ($root === null){
            return 0;
        }
        $depth = 1;
        $queue = [$root];
        while(!empty($queue)) {
            $count = count($queue);
            for($start = 0; $start < $count; $start++) {
                $node = array_shift($queue);
                if ($node->left === null && $node->right === null){
                    return $depth;
                }
                if ($node->left !== null) {
                    $queue[] = $node->left;
                }
                if ($node->right !== null) {
                    $queue[] = $node->right;
                }
            }
            ++$depth;
        }
    }
}

Last updated