NC13题解 | #二叉树的最大深度#
二叉树的最大深度
http://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73
- 解法1:递归dfs
- 解法2:队列bfs层序遍历
解法1:递归
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
public int maxDepth (TreeNode root) {
// write code here
if(root == null) {
return 0;
}
int res = dfs(root,0);
return res;
}
//递归dfs遍历
public int dfs(TreeNode root, int depth){
if(root == null) {
return depth;
}
if(root.left == null && root.right == null){
return depth+1;
}
return Math.max(dfs(root.left,depth+1),dfs(root.right,depth+1));
}
}
解法2:队列bfs层序遍历
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
public int maxDepth (TreeNode root) {
// write code here
if(root == null) {
return 0;
}
int res = bfs(root);
return res;
}
//队列层序遍历
public int bfs(TreeNode root){
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int res = 0;
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode node = queue.poll();
//list放入null会占用一个空间,
//list加入null判断isEmpty结果是否,size同样会加1
if(node.left != null){
queue.add(node.left);
}
if(node.right != null){
queue.add(node.right);
}
}
res++;
}
return res;
}
}