/* 递归解法 O(n)
1。如果二叉树为null,则二叉树的深度为0;
2. 如果二叉树不为null,则二叉树的深度=max(左子树的深度,右子树的深度)+1;
public static int getDepthRec(TreeNode root){
if(root == null){
return 0;
}
int leftDepth = getDepthRec(root.left);
int rightDepth = getDepthRec(root.right);
return Math.max(leftDepth,rightDepth)+1;
}
/* 迭代解法O(n)
基本思想同LevelOrderTravelsal,还是用一个Queue。
*/
public static int getDepth(TreeNode root){
if(root == null){
return 0;
}
int depth = 0;//深度
int currentLevelNodes = 1;//当前level,node的数量
int nextLevelNodes = 0;//下一层,node的数量
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode cur = queue.remove();//从队头的位置移除
currentLevelNodes--;//减少当前level node数量
if(cur.left != null)( //如果有左孩子,则加到队尾
queue.add(cur.left);
nextLevelNodes++;//并增加下一层Level Node 的数量
)
if(cur.right != null){//如果有右孩子,加到队尾
queue.add(cur.right);
nextLevelNodes++;
}
if(currentLevelNodes == 0){//已经遍历完当前层的所有节点
depth ++; //增加高度
currentLevelNodes = nextLevelNodes;//初始化下一层
nextLevelNodes = 0;
}
}
return depth;
}
转载于:https://my.oschina.net/u/2477353/blog/662937