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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3/ \9 20/ \15 7
return its minimum depth = 2.
题意
找到给定树从根到叶结点(两子树都为空的结点)的最短距离。
思路
递归或迭代。
代码实现 - 递归
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/class Solution {public int minDepth(TreeNode root) {if (root == null) {return 0;}int lDepth = minDepth(root.left);int rDepth = minDepth(root.right);if (lDepth == 0) {return rDepth + 1;} else if (rDepth == 0) {return lDepth + 1;} else {return Math.min(lDepth, rDepth) + 1;}}}
代码实现 - 迭代
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/class Solution {public int minDepth(TreeNode root) {if (root == null) {return 0;}Queue<TreeNode> q = new ArrayDeque<>();int depth = 0;q.offer(root);while (!q.isEmpty()) {depth++;int size = q.size();for (int i = 0; i < size; i++) {TreeNode cur = q.poll();// 第一次找到叶结点,说明已经为最短距离if (cur.left == null && cur.right == null) {return depth;}if (cur.left != null) {q.offer(cur.left);}if (cur.right != null) {q.offer(cur.right);}}}return depth;}}
