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.
递归解法
class Solution {
public int maxDepth(TreeNode root) {
if(root==null)
return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}
迭代解法
采用BFS的思想,当每层搜索完后,如果还有下一层则将最大深度+1.
class Solution {
public int maxDepth(TreeNode root) {
if(root==null)
return 0;
Queue<TreeNode> q=new LinkedList<>();
q.add(root);
int depth=0;
while(!q.isEmpty())
{
depth++;
int levelNum=q.size();
for(int i=0;i<levelNum;++i)
{
TreeNode t=q.poll();
if(t.left!=null)
q.add(t.left);
if(t.right!=null)
q.add(t.right);
}
}
return depth;
}
}