1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| 思路: 判读树的左右节点是否至少存在其一,存在则深度加一,以子节点进行递归,返回最终深度
代码: function maxDepth($root) { return $this->depth($root); }
function depth($node, $depth = 1) { if (!$node){ return 0; }
// 不存在子节点,返回当前深度 if (!$node->left && !$node->right) { return $depth; }
return max($this->depth($node->right, $depth + 1), $this->depth($node->left, $depth + 1)); }
|