白银挑战:二叉树的深度和高度问题
1.求二叉树的最大深度(利用后序遍历)
对于树中的每个节点,假设都存在左子树和右子树,那么当前节点的高度就是左子树高度left和右子树高度right二者最大值,然后加上当前节点所处高度1,才是以当前节点为头节点的整棵树的高度;重复以上过程就能够得到整棵树的最大高度;
代码如下:
public static int getMaxHeight(TreeNode root){
if(root == null){
return 0;
}
int left = getMaxHeight(root.left); // 先遍历左子树,得到左子树的深度
int right = getMaxHeight(root.right); // 再遍历右子树,得到右子树的深度
return Math.max(left,right)+1; //最后处理当前节点
}
2.求二叉树的最小深度
解题思路:对于这道题需要考虑的周全:如果root节点的左子树为null,那么root节点的最小高度即是root的右子树的最小高度+1;并不是1;同理如果root的右子树为null,而左子树不为null,那么root的最小高度即是左子树的最小高度+1;
代码如下:
public static int minDepth(TreeNode root) {
// 如果root为null,返回0
if(root == null){
return 0;
}
// 如果root 为叶子节点,返回1即可
if(root.left == null && root.right == null){
return 1;
}
// 定义当前节点返回的最小深度
int depth=Integer.MAX_VALUE;
// 如果左子树不为null,那么就让depth和左子树的深度比较,取最小值
if(root.left != null){
depth=Math.min(minDepth(root.left),depth);
}
// 如果右子树不为null,那么就让depth和右孩子的深度比较,取最小值
if(root.right != null){
depth=Math.min(minDepth(root.right),depth);
}
// 返回的结果+1 是因为当前节点也要算进去
return depth+1;
}
3.N叉树的最大深度问题
解题思路和二叉树的最大深度一样,不过是利用for循环去遍历当前节点的每一个子树;寻找子树的最大高度,然后+root节点本来的高度1;即是整棵树的最大深度;
代码如下:
public static int maxDepth(Node root) {
if(root == null){
return 0;
}
// 需要判断当前节点的子树是否为null;
if(root.children.isEmpty()){
return 1;
}
int maxDepth=0;
List<Node> nodeList=root.children;
// 遍历每个子树,得到子树的最大高度;
for(int i=0;i<nodeList.size();i++){
maxDepth=Math.max(maxDepth,maxDepth(nodeList.get(i)));
}
return maxDepth+1;
}