一、递归实现
public void treeDepth(TreeNode node){
if(node == null){
return 0;
}
int leftDepth=treeDepth(node.left);
int rightDepth=treeDepth(node.right);
return leftDepth>rightDepth?(leftDepth+1):(rightDepth+1);
}
二、非递归实现
public void treeDepthByQuene(TreeNode node){
if(node == null){
return 0;
}
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.add(node);
int cur,last;
int depth=0;
TreeNode current=null;
while(!queue.isEmpty()){
cur=0;
last=queue.size();
while(cur<last){
current=queue.poll();
cur++;
if(current.left!=null){
queue.add(current.left);
}
if(current.right!=null){
queue.add(current.right);
}
}
depth++;
}
return depth;
}