递归法
class Solution {
public int maxDepth(TreeNode root) {
if(root==null)return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}
迭代法
利用队列,将每一层的节点都入队然后分别将它们的左孩子和右孩子节点入队直至队列为空。每次遍历完一层的节点深度depth就加一。
class Solution {
public int maxDepth(TreeNode root) {
if(root==null)return 0;
Queue<TreeNode> q=new LinkedList<>();
q.offer(root);
int depth=0;
while(!q.isEmpty()){
int size=q.size();
while(size!=0){
root=q.poll();
if(root.left!=null){
q.offer(root.left);
}
if(root.right!=null){
q.offer(root.right);
}
size--;
}
depth++;
}
return depth;
}
}