输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
递归形式
/**
*输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
*/
public int RMaxDeepth(TreeNode head){
/**思路
* 设置一个记录maxDeep,分别对根节点的左子树和右子树递归的进行遍历,如果存在左子树或者存在右子树,深度加1即可
* 最后返回根节点左右子树中深度最大的那个即可。
*
* */
if (head==null){
return 0;
}
int maxDeep=1;//因为根节点算一层
int leftDeep=0;
int rightDeep=0;
leftDeep=leftDeep+RMaxDeepth(head.left);
rightDeep=rightDeep+RMaxDeepth(head.right);
maxDeep+=Math.max(leftDeep,rightDeep);
return maxDeep;
}
非递归形式。采用层序遍历
/**
* 非递归,这里使用了层序遍历
*/
public int TreeDepth(TreeNode pRoot)
{
if(pRoot == null){
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(pRoot);
int depth = 0, count = 0, nextCount = 1;
while(queue.size()!=0){
TreeNode top = queue.poll();
count++;
if(top.left != null){
queue.add(top.left);
}
if(top.right != null){
queue.add(top.right);
}
if(count == nextCount){
nextCount = queue.size();
count = 0;
depth++;
}
}
return depth;
}
类比:给定二叉树,找到它的最小深度。最小深度是沿从根节点到最近的叶节点的最短路径上的节点数。
一个求最小深度,一个求最大深度。
/**
* 给定二叉树,找到它的最小深度。最小深度是沿从根节点到最近的叶节点的最短路径上的节点数。
*/
public int MinDeepth(TreeNode head){
/**思路
* 这里还是用层序遍历的方法。
*
* */
if (head==null)return 0;
Queue<TreeNode> queue=new LinkedList<>();
queue.add(head);
int depth=1;//head为1层
while (!queue.isEmpty())
{
int size=queue.size();
for (int i=0;i<size;i++){//每次遍历这么一层
TreeNode temp=queue.poll();
if (temp.left!=null){
queue.add(temp.left);
}
if (temp.right!=null){
queue.add(temp.right);
}
if (temp.right==null&&temp.left==null){
return depth;
}
}
depth++;
}
return depth;
}