0111. Minimum Depth of Binary Tree (E)

Minimum Depth of Binary Tree (E)

题目

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.


题意

找到给定树从根到叶结点(两子树都为空的结点)的最短距离。

思路

递归或迭代。


代码实现

Java

递归

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;
        }
    }
}

迭代

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;
    }
}

JavaScript

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var minDepth = function (root) {
  if (!root) {
    return 0
  }

  return (
    (!root.left
      ? minDepth(root.right)
      : !root.right
      ? minDepth(root.left)
      : Math.min(minDepth(root.left), minDepth(root.right))) + 1
  )
}
posted @ 2020-10-22 15:48  墨云黑  阅读(88)  评论(0编辑  收藏  举报