leetcode 104 二叉树的最大深度
此题有两个思路:
第一个就是递归,向左右子树进行递归,当到达叶子结点的时候返回0,然后比较左右子树的深度哪个大,并返回最大值+1。
左子树和右子树的最大深度 ll 和 rr,那么该二叉树的最大深度即为max(l,r)+1。代码如下:
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
int leftHeight = maxDepth(root.left);
int rightHeight = maxDepth(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
}
}
第二个思路则是使用BFS,每遍历一层就深度就加一,直到所有结点都被访问过。代码如下:
class Solution {
public int maxDepth(TreeNode root) {
if(root == null)
return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int ans = 0;
while(!queue.isEmpty()){
int size = queue.size();
while(size>0){
TreeNode t = queue.poll();
if(t.left!=null){
queue.offer(t.left);
}
if(t.right!=null){
queue.offer(t.right);
}
--size;
}
ans++;
}
return ans;
}
}