迭代
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
int de=0;
Queue<TreeNode> qu=new LinkedList<>();
TreeNode tn;
int le;
qu.offer(root);
while(!qu.isEmpty()){
le=qu.size();
while(le>0){
tn=qu.poll();
if(tn.left!=null){
qu.offer(tn.left);
}
if(tn.right!=null){
qu.offer(tn.right);
}
le--;
}
de++;
}
return de;
}
}
class Solution(object):
def maxDepth(self, root):
if root is None:
return 0
de=0
qu=collections.deque()
qu.append(root)
while qu:
le=len(qu)
while le>0:
tn=qu.popleft()
if tn.left:
qu.append(tn.left)
if tn.right:
qu.append(tn.right)
le-=1
de+=1
return de
递归
class Solution {
public int maxDepth(TreeNode root) {
int de=0;
TreeNode nod=root;
return Explore(root,de);
}
int Explore(TreeNode nod,int de){
if(nod==null){
return de;
}
de++;
return Math.max(Explore(nod.left,de),Explore(nod.right,de));
}
}
class Solution(object):
def maxDepth(self, root):
de=0
nod=root
def Explore(nod,de):
if nod is None:
return de
de+=1
return max(Explore(nod.left,de),Explore(nod.right,de))
return Explore(root,de)