File tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed
Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change @@ -216,6 +216,83 @@ class Solution:
216216 return depth
217217```
218218
219+ Go Code:
220+ ``` go
221+ /* *
222+ * Definition for a binary tree node.
223+ * type TreeNode struct {
224+ * Val int
225+ * Left *TreeNode
226+ * Right *TreeNode
227+ * }
228+ */
229+ // BFS
230+ func maxDepth (root *TreeNode ) int {
231+ if root == nil {
232+ return 0
233+ }
234+
235+ depth := 1
236+ q := []*TreeNode{root, nil } // queue
237+ var node *TreeNode
238+ for len (q) > 0 {
239+ node, q = q[0 ], q[1 :] // pop
240+ if node != nil {
241+ if node.Left != nil {
242+ q = append (q, node.Left )
243+ }
244+ if node.Right != nil {
245+ q = append (q, node.Right )
246+ }
247+ } else if len (q) > 0 { // 注意要判断队列是否只有一个 nil
248+ q = append (q, nil )
249+ depth++
250+ }
251+ }
252+ return depth
253+ }
254+ ```
255+
256+ PHP Code:
257+ ``` php
258+ /**
259+ * Definition for a binary tree node.
260+ * class TreeNode {
261+ * public $val = null;
262+ * public $left = null;
263+ * public $right = null;
264+ * function __construct($value) { $this->val = $value; }
265+ * }
266+ */
267+ class Solution
268+ {
269+
270+ /**
271+ * @param TreeNode $root
272+ * @return Integer
273+ */
274+ function maxDepth($root)
275+ {
276+ if (!$root) return 0;
277+
278+ $depth = 1;
279+ $arr = [$root, null];
280+ while ($arr) {
281+ /** @var TreeNode $node */
282+ $node = array_shift($arr);
283+ if ($node) {
284+ if ($node->left) array_push($arr, $node->left);
285+ if ($node->right) array_push($arr, $node->right);
286+ } elseif ($arr) {
287+ $depth++;
288+ array_push($arr, null);
289+ }
290+ }
291+ return $depth;
292+ }
293+ }
294+ ```
295+
219296** 复杂度分析**
220297
221298- 时间复杂度:$O(N)$
You can’t perform that action at this time.
0 commit comments