LeetCode 559 N叉树的最大深度

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43870742/article/details/102484152

给定一个 N 叉树,找到其最大深度。

最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

例如,给定一个 3叉树 :

我们应返回其最大深度,3。

说明:

树的深度不会超过 1000。
树的节点总不会超过 5000。

Js:

普通的递归,其实和前面做过的二叉树并没有太多区别。

/**
 * // Definition for a Node.
 * function Node(val,children) {
 *    this.val = val;
 *    this.children = children;
 * };
 */
/**
 * @param {Node} root
 * @return {number}
 */
var maxDepth = function(root) {
    if (!root) {
        return 0
    }
    if (!root.children) {
        return 1
    }
    console.log(root.children)
    res = 0
    for (child in root.children) {
        res = Math.max(res, maxDepth(root.children[child]))
    }
    return res+1
};
 

猜你喜欢

转载自blog.csdn.net/weixin_43870742/article/details/102484152
今日推荐