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.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its depth = 3.
解题思路
- 使用bfs 每层遍历对层数计数 输出
- 使用dfs,从根节点深度搜索返回最大值
解题代码
bfs solution 遍历每层加一输出深度即可
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> q = new LinkedList<>();
int level = 0;
q.add(root);
while (!q.isEmpty()){
int qsize = q.size();
for (int i = 0; i < qsize; i++){
TreeNode node = q.poll();
if (node.left != null)
q.add(node.left);
if (node.right != null)
q.add(node.right);
}
level += 1;
}
return level;
}
}
dfs solution
dfs计算深度的问题 本题和第110 ,111题中计算深度的思想一致 , 和本题非常的类似
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};