给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [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() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
解法一:广度优先搜索(BFS)
BFS的意思就是一层一层的遍历,那么完成这一步的核心步骤就是使用队列(先进先出)把每一层的node放入队列里。
这一题就是使用队列把每一层的node放入队列,完成一层就height++,遍历当前层的node时,如果其left或者right不为空,则把这一个node加入队列,当queue为空时,说明root已遍历完成,返回height即可。
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int height = 0;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int len = queue.size();
for(int i = 0;i<len;i++){
TreeNode node = queue.pollFirst();
if(node.left != null){
queue.add(node.left);
}
if(node.right != null){
queue.add(node.right);
}
}
height++;
}
return height;
}
}
解法二:深度优先搜索(DFS)
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;//这里会往更深的层数找,最终一定会走到root为null的时候,则返回0,不要在这里纠结了。
}
}