Sunday, April 17, 2022

[LeetCode] 104. Maximum Depth of Binary Tree

    

"踏上LeetCode解題之路,順手紀錄一下PHP練功的過程囉。這是第十一篇~~"


Maximum Depth of Binary Tree - LeetCode


思考過程

待補上


結果

/**
 * 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 maxDepth($root) {
        
        if ($root === null) {
            return 0;
        }
        
        $sum= 1+ max($this->maxDepth($root->left), $this->maxDepth($root->right));
        return $sum;
    }
}

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

    /**
     * @param TreeNode $root
     * @return Integer
     */
    function maxDepth($root) {
        
        if ($root === null) {
            return 0;
        }
        
        $left = $this->maxDepth($root->left)+1;
        $right = $this->maxDepth($root->right)+1;
        
        return ($left > $right) ? $left : $right;
    }
}



Contact Form

Name

Email *

Message *