LeetCode 第104题:二叉树的最大深度
2020-08-06 本文已影响0人
放开那个BUG
1、前言
题目描述2、思路
采用 DFS 或者 BFS 都可以。
3、代码
DFS:
/**
* 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) {
if(root == null){
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}
BFS:
/**
* 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) {
if(root == null){
return 0;
}
int depth = 0;
List<TreeNode> queue = new ArrayList<>();
queue.add(root);
while(queue.size() > 0){
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode cur = queue.remove(0);
if(cur.left != null){
queue.add(cur.left);
}
if(cur.right != null){
queue.add(cur.right);
}
}
depth++;
}
return depth;
}
}