二叉树的最大深度计算
方法一
思路:应用递归的方法,分别计算左子树与右子树的深度,之后比较两个子树的最大值,使其加1(根节点),得出最大深度。
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
int left = maxDepth(root.left);
int rigth = maxDepth(root.right);
return Math.max(left , rigth)+1;
}
}
方法二:
思路:引入一个队列作为辅助容器,类似于上一篇博客的层序遍历实现方法,代码如下:
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int depth = 0;
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
size--;
}
depth++;
}
return depth;
}
}