算法1
宽搜实现,其实就是计算当前二叉树的层数
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int treeDepth(TreeNode root) {
if (root == null)
return 0;
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
int deep = 0;
while (!queue.isEmpty()){
int size = queue.size();
while (size > 0){
TreeNode p = queue.poll();
if (p.left != null)
queue.offer(p.left);
if (p.right != null)
queue.offer(p.right);
size--;
}
deep++;
}
return deep;
}
}
算法2
递归实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int treeDepth(TreeNode root) {
if (root == null)
return 0;
int res = 1;
return res + Math.max(treeDepth(root.left),treeDepth(root.right));
}
}