Leetcode学习笔记:#104. Maximum Depth of Binary Tree
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.
Note: A leaf is a node with no children.
实现:
public int maxDepth(TreeNode root){
if(root == null)
return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int count = 0;
while(!queue.isEmpty()){
int size = queue.size();
while(size-- > 0){
TreeNode node = queue.pull();
if(node.left != null)
queue.offer(node.left);
if(node.right != null)
queue.offer(node.right);
}
count++;
}
return count;
思路:
BFS,用一个队列来表示树的高度,每遍历到新一层+1