为什么80%的码农都做不了架构师?>>>
问题:
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.
解决:
① 本题要求求二叉树的最小深度,首先使用递归的解法。
public class Solution {//1ms
public int minDepth(TreeNode root) {
if(root == null) return 0;
if(root.left == null) return minDepth(root.right) + 1;
if(root.right == null) return minDepth(root.left) + 1;
return Math.min(minDepth(root.left),minDepth(root.right)) + 1;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {//0ms
public int minDepth(TreeNode root) {
if(root == null) return 0;
int left = minDepth(root.left);
int right = minDepth(root.right);
return (left == 0 || right == 0) ? left + right + 1: Math.min(left,right) + 1;
}
}
② 使用非递归的方法,对二叉树进行BFS(广度优先搜索),由于是按层遍历的,因此如果在某一层发现了一个叶子节点,那么就找到了最小深度,此时返回当前深度即可。
public class Solution {//1ms
public int minDepth(TreeNode root) {
if(root == null) return 0;
LinkedList<TreeNode> queue = new LinkedList();
int level = 0;
queue.add(root);
while(! queue.isEmpty()){
int levelLen = queue.size();
level ++;
for (int i = 0;i < levelLen ;i ++ ) {
TreeNode node = queue.removeFirst();
if(node.left == null && node.right == null) return level;
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
}
return level;
}
}