资讯专栏INFORMATION COLUMN

[LeetCode] 559. Maximum Depth of N-ary Tree

EdwardUp / 516人阅读

Problem

Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

For example, given a 3-ary tree:

We should return its max depth, which is 3.

Note:

The depth of the tree is at most 1000.
The total number of nodes is at most 5000.

Solution
/*
// Definition for a Node.
class Node {
    public int val;
    public List children;

    public Node() {}

    public Node(int _val,List _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
    public int maxDepth(Node root) {
        return helper(root);
    }
    private int helper(Node root) {
        if (root == null) return 0;
        int maxDepth = 1;
        for (Node node: root.children) {
            maxDepth = Math.max(maxDepth, 1+helper(node));
        }
        return maxDepth;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77378.html

相关文章

  • Leetcode PHP题解--D42 559. Maximum Depth of N-ary Tr

    摘要:题目链接题目分析此题和上一题思路一样。只是不是二叉树。思路略最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D42 559. Maximum Depth of N-ary Tree 题目链接 559. Maximum Depth of N-ary Tree 题目分析 此题和上一题思路一样。只是不是二叉树。而是正常的树。 思路 略 最终代码

    CrazyCodes 评论0 收藏0
  • [LeetCode] 429. N-ary Tree Level Order Traversal (

    429. N-ary Tree Level Order Traversal Given an n-ary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level). For example, given a 3-ary tree:showImg(https...

    LiangJ 评论0 收藏0
  • leetcode429. N-ary Tree Level Order Traversal

    摘要:题目要求对叉树进行水平遍历,并输出每一行遍历的结果。因此无需再用队列来额外存储每一行的水平遍历,可以直接通过递归将遍历结果插入到相应行的结果集中。 题目要求 Given an n-ary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level)...

    tomlingtm 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • LeetCode 104 Maximum Depth of Binary Tree 二叉树最大深度

    LeetCode 104 Maximum Depth of Binary Tree难度:Easy 题目描述:找到一颗二叉树的最深深度。Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down ...

    PiscesYE 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<