题意:给定一个二叉树,查找其最小深度。
初步分析:递归的获取到最小深度。(从上往下,左右子树深度相比,每次递归都取最小的那个再加1)
public class Solution {
public int minDepth(TreeNode root) {
if(root == null)
return 0;
return Math.min(minDepth(root.left),minDepth(root.right))+1;
}
}
但是,这样有错
左右子树有一个为空的时候,那么min就直接就是0了(不管另一个子树有多高)
也就是说不管是
* 还是 *
*
高度都是1,显然是不对的。
比如:
a
b
返回1.但应该是2,因为结点b的高度为1(min(0,0)+1),但是a的高度为(min(b,0)+1)即(min(1,0)+1)即1.
我们发现,左结点或者右结点有一者不为空的时候,取小的时候会直接抹掉另一个子树的高度。
所以这种情况应该直接取不为空那一边子树的高度(再加1)
深度优先搜索:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root == null)
return 0;
int dep = 0;
if(root.left!=null && root.right!=null)
dep = Math.min(minDepth(root.left),minDepth(root.right));
if(root.left == null) //左子树为空,右子树不为空,取右子树的高度
dep = minDepth(root.right);
if(root.right == null) //右子树为空。左子树不为空,取左子树的高度
dep = minDepth(root.left);
return dep+1;
}
}
广度优先搜索(将每一层不是叶子结点的放入层次遍历队列中,每次取出一层,每遍历一层高度加一,直到遇到叶子节点为止):
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int depth = 1; //按层记高度,根节点是第一层,高度为一
while (!queue.isEmpty()) {
int l = queue.size();
for (int i = 0; i < l; i++) {
TreeNode n = queue.poll(); //取出当前层所有结点
if (n.left == null && n.right == null) { //到叶子节点就返回高度
return depth;
}
if (n.left != null) { //将不为空的结点放入下一层(只要不是叶子节点(左右都为空)就要继续计数)
queue.add(n.left);
}
if (n.right != null) {
queue.add(n.right);
}
}
depth++; //每一层,高度加一
}
return depth;
}