1. 二叉树的最大深度
/**
* 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(!isset($root)){
return 0;
}
$leftDepth = $rightDepth = 0;
if(isset($root->left)){
$leftDepth = $this->maxDepth($root->left);
}
if(isset($root->right)){
$rightDepth = $this->maxDepth($root->right);
}
return ($rightDepth > $leftDepth ? $rightDepth : $leftDepth) + 1;
}
}
2. 二叉树的最小深度
/**
* 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(!isset($root)){
return 0;
}
$leftDepth = $rightDepth = 0;
if(isset($root->left)){
$leftDepth = $this->minDepth($root->left);
}
if(isset($root->right)){
$rightDepth = $this->minDepth($root->right);
}
// 左子树为0,返回右子树深度+1,或者右子树为0,返回左子树深度+1
if ($leftDepth == 0 || $rightDepth == 0) {
return $leftDepth + $rightDepth + 1;
}
return ($rightDepth > $leftDepth ? $leftDepth : $rightDepth) + 1;
}
}