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.
求二叉树的最短深度
解法一:深度优先遍历DFS
/**
* 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 l = minDepth(root.left);
int r = minDepth(root.right);
if (l == 0 && r == 0) return 1;
if (l == 0 ) {
l = Integer.MAX_VALUE;
}
if (r == 0) {
r= Integer.MAX_VALUE;
}
return Math.min(l, r)+1;
}
}
解法一:广度优先遍历BFS
public class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
LinkedList<TreeNode> currLevel = new LinkedList<TreeNode>();
currLevel.add(root);
int count = 1;
while (!currLevel.isEmpty()) {
LinkedList<TreeNode> nextlevel = new LinkedList<TreeNode>();
while (!currLevel.isEmpty()) {
TreeNode node = currLevel.poll();
if (node.left == null && node.right == null) return count;
if (node.left != null) nextlevel.add(node.left);
if (node.right != null) nextlevel.add(node.right);
}
count++;
currLevel = nextlevel;
}
return count;
}
}