[leetcode]二叉树的最大深度

题目描述

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

   3
 / \
9  20
  /  \
 15   7

返回它的最大深度 3 。

算法实现

递归版(php)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 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 {
public $max_depth=0;

/**
* @param TreeNode $root
* @return Integer
*/
function maxDepth($root) {
$this->doTraverse($root,1);
return $this->max_depth;
}
function doTraverse($node,$depth){
if($node==null){
return;
}
$this->max_depth = max($this->max_depth,$depth);
++$depth;
$this->doTraverse($node->left,$depth);
$this->doTraverse($node->right,$depth);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 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) {
return $root == null?0:max($this->maxDepth($root->left),$this->maxDepth($root->right))+1;
}
}

迭代版(php)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* 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 {
public $stack = [];

/**
* @param TreeNode $root
* @return Integer
*/
function maxDepth($root) {
$depth = 0;
if($root==null){
return $depth;
}
$node = $root;
$this->stack[] = $node;
do{
$count = count($this->stack);
while($count>0){
$node = array_shift($this->stack);
if($node->left!=null){
$this->stack[] = $node->left;
};
if($node->right!=null){
$this->stack[] = $node->right;
}
$count--;
}
$depth++;
}while(!empty($this->stack));

return $depth;
}
}

参考

二叉树的最大深度