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

16、二叉树的最小深度 #16

Open
conan1992 opened this issue Apr 13, 2020 · 0 comments
Open

16、二叉树的最小深度 #16

conan1992 opened this issue Apr 13, 2020 · 0 comments
Labels

Comments

@conan1992
Copy link
Owner

题目描述:

给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7]
image
返回它的最小深度 2.
image
需要注意的是题目中标注的说明,叶子结点是指没有子节点的节点
image
所以此题的最小深度为3.

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var minDepth = function(root) {
    if(!root){
        return 0
    }else if(root.left&&root.right){
        return 1 + Math.min(minDepth(root.left), minDepth(root.right))
    }else if(root.left){
        return 1 + minDepth(root.left)
    }else if(root.right){
        return 1 + minDepth(root.right)
    }else{
        return 1
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant