难度:easy
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode() {}
- * TreeNode(int val) { this.val = val; }
- * TreeNode(int val, TreeNode left, TreeNode right) {
- * this.val = val;
- * this.left = left;
- * this.right = right;
- * }
- * }
- */
- class Solution {
- public int minDepth(TreeNode root) {
- // int minDepth = Integer.MAX_VALUE;
- if (root == null) {
- return 0;
- }
- Queue
queue = new LinkedList<>(); - queue.offer(root);
- int depth = 0;
- while (!queue.isEmpty()) {
- int size = queue.size();
- // 层数+1
- depth++;
- for (int i = 0; i < size; i++) {
- TreeNode node = queue.poll();
- // 一个节点不存在左节点和右节点就可以计算深度;
- if (node.left == null && node.right == null) {
- // minDepth = Math.min(minDepth, depth);
- return depth;
- }
- if (node.left != null) {
- queue.offer(node.left);
- }
- if (node.right != null) {
- queue.offer(node.right);
- }
- }
- }
-
- return minDepth;
- }
- }
在leetcode看到一个不错的题解,通过自行封装QueueNode加入depth信息,随时可以获得最短的深度。
- class Solution {
- class QueueNode {
- TreeNode node;
- int depth;
-
- public QueueNode(TreeNode node, int depth) {
- this.node = node;
- this.depth = depth;
- }
- }
-
- public int minDepth(TreeNode root) {
- if (root == null) {
- return 0;
- }
-
- Queue
queue = new LinkedList(); - queue.offer(new QueueNode(root, 1));
- while (!queue.isEmpty()) {
- QueueNode nodeDepth = queue.poll();
- TreeNode node = nodeDepth.node;
- int depth = nodeDepth.depth;
- if (node.left == null && node.right == null) {
- return depth;
- }
- if (node.left != null) {
- queue.offer(new QueueNode(node.left, depth + 1));
- }
- if (node.right != null) {
- queue.offer(new QueueNode(node.right, depth + 1));
- }
- }
-
- return 0;
- }
- }