1.树的最大深度
递归
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
public int maxDepth (TreeNode root) {
// write code here
if(root==null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}
非递归——层次遍历(Queue<TreeNode> q=new LinkedList<>();)
public int maxDepth (TreeNode root) {
if(root==null) return 0;
Queue<TreeNode> q=new LinkedList<>();
q.add(root);
int res=0;
while(!q.isEmpty()){
int count=q.size();
for(int i=0;i<count;i++){
TreeNode t=q.poll();
if(t.left!=null) q.add(t.left);
if(t.right!=null) q.add(t.right);
}
res++;
}
return res;
}