给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回它的最大深度 3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
- 递归(深度优先)
递归到最底层后一层层返回,有节点返回1,没节点返回零,取返回的两个子节点的最大数
/**
* 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) return 0;
return 1 + max($this->maxDepth($root->left), $this->maxDepth($root->right));
}
}
- 迭代(广度优先)BFS
一层一层扫描,把节点先放入队列中后对其子节点进行循环并放入队列中。所有节点节点遍历完毕后,shift出当前节点(此时队列中只有当前节点的子节点)。当队列中完全没有同层节点后,depth++。一直循环这个队列直至没有值(即,已经遍历完所有节点并且所有节点都没有子节点了)
/**
* 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) return 0;
$nodes = [$root];
$depth = 1;
while(1) {
foreach ($nodes as $node) {
if ($node->left) {
array_push($nodes, $node->left);
}
if ($node->right) {
array_push($nodes, $node->right);
}
array_shift($nodes);
}
if (!$nodes) return $depth;
$depth++;
}
}
}