Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二叉树的最小深度 #86

Open
louzhedong opened this issue Nov 19, 2018 · 0 comments
Open

二叉树的最小深度 #86

louzhedong opened this issue Nov 19, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处 LeetCode 算法第111题

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最小深度 2.

思路

采用递归的方式

解答

/**
 * @param {TreeNode} root
 * @return {number}
 */

var calculateDepth = function (root) {
  if (!root.left && !root.right) {
    return 1;
  }

  if (!root.left) {
    return calculateDepth(root.right) + 1;
  }
  if (!root.right) {
    return calculateDepth(root.left) + 1;
  }

  return Math.min(calculateDepth(root.left), calculateDepth(root.right)) + 1;
}
var minDepth = function (root) {
  if (!root) return 0;
  var depth = calculateDepth(root);
  return depth;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant