Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
1、递归解法。两行
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
2、非递归解法。队列
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int result = 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
int size = queue.size();
for(int i=0; i<size; i++) {
TreeNode curr = queue.poll();
if(curr.left !=null) queue.offer(curr.left);
if(curr.right !=null) queue.offer(curr.right);
}
result ++;
}
return result ;
}