Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
-
深度优先遍历(递归)
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int run(TreeNode root) {
if(root == null)
return 0;
if(root.right == null && root.left == null)
return 1;
int leftLen = Integer.MAX_VALUE;
int rightLen = Integer.MAX_VALUE;
if(root.left != null)
leftLen = run(root.left)+1;
if(root.right != null)
rightLen = run(root.right)+1;
return leftLen < rightLen ? leftLen : rightLen;
}
}
2. 广度优先遍历
与二叉树的层序遍历类似。
一旦找到一个叶子节点,那么这个节点肯定是离根节点最短的叶子节点。这个方法因为不用遍历整棵树所以它的效率要比深度优先遍历方法高。
/**
利用层序遍历(广度优先)找出第一个叶子节点,此为离根节点最短路径的节点。
**/
public int run(TreeNode root){
if(root == null)
return 0;
if(root.right == null && root.left == null)
return 1;
int count = 0; //二叉树的层数
LinkedList<TreeNode> treeNodeQueue = new LinkedList<>();
if(treeNodeQueue.offer(root)) {
while (!treeNodeQueue.isEmpty()) {
count++;
//遍历二叉树的某一层
int size = treeNodeQueue.size();
for (int i = 0; i < size; i++) {
TreeNode treeNode = treeNodeQueue.poll();
if (treeNode.left == null && treeNode.right == null)
return count; //如果找到叶子节点,直接返回层数
if (treeNode.left != null)
treeNodeQueue.offer(treeNode.left);
if (treeNode.right != null)
treeNodeQueue.offer(treeNode.right);
}
}
}
return count;
}