104. 二叉树的最大深度
难度简单549
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
}
}
题解:
-
方法一(递归):
在这里我们可以采用递归的方式进行解题,从图给的图示来看,我们可以发现 节点1 的树高就是它自己子树 节点为2 的树高+1; 节点2 的树高又是 它自己子树 节点为4的树高+1; 其实也就是自己左子树或右子树当中最大的树高+1。
class Solution public int maxDepth(TreeNode root) { if (root == null) { return 0; } return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; } }
-
方法二(迭代):
利用迭代时,我们需要借用层次遍历的一个思想,我们每遍历一层的时候,可以取出它的左右子节点,并加入到一个队列当中。当一层中的最后一个节点从队列中取出后,并将其左右子树加入队列中,此时的队列长度就应该为下一层的节点个数。
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
// 树高
int height= 0;
// 每一层的节点数量
int levelCount = 1;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()){
TreeNode node = queue.poll();
levelCount--;
if(node.left != null ){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
if(levelCount == 0){
levelCount = queue.size();
height++;
}
}
return height;
}
}