求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。
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.
分析:不管对什么二叉树,一个左分支,一个右分支,结果返回子分支的最小深度加1,所以用递归
注意细节:如果有一个分支不为空,则返回另一个分支;如果节点数为null,返回0
public class TreeNode {int val = 0;TreeNode left = null;TreeNode right = null;}
代码:
public class Solution {/**** @param root TreeNode类* @return int整型*/public int run (TreeNode root) {if(root == null) {return 0;}int left = run(root.left);int right = run(root.right);if(left==0) {return right+1;}if(right==0) {return left+1;}return (left<=right?left:right)+1;}}
对于求最小深度,bfs的方法虽然空间复杂度会更高,但是理论上效率会更快。
bfs代码如下:
public int minDepth(TreeNode root) {if (root == null) {return 0;}Queue<TreeNode> queue = new LinkedList<>();queue.add(root);int deep = 0;while (!queue.isEmpty()) {int size = queue.size();deep++;for (int i = 0; i < size; i++) {TreeNode node = queue.poll();if (node.left == null && node.right == null) {return deep;}if (node.left != null) {queue.offer(node.left);}if (node.right != null) {queue.offer(node.right);}}}return deep;}
