题目:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
返回它的最大深度 3 。
思路一:
采用深度优先遍历的思想,进行递归,对左右子树的深度进行遍历,在取左右字数最深的深度
大小值判断提示:
1.a>=b?a+1:b+1;是一个冒号表达式
2.大小值判断也可以用Math.max(a,b)
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
int a=0,b=0;
a = maxDepth(root.left);
b = maxDepth(root.right);
return a>=b?a+1:b+1;
}
}
}
或者直接使用函数的写法
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
int l=maxDepth(root.left);
int r=maxDepth(root.right);
return Math.max(l,r)+1;
}
}
思路二:
使用广度优先遍历
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int ans = 0;
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
size--;
}
ans++;
}
return ans;
}
}