首页 > 其他分享 >leetcode-559-easy

leetcode-559-easy

时间:2023-01-22 20:13:17浏览次数:38  
标签:559 max depth easy ary null root leetcode

Maximum Depth of N-ary Tree

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.

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

Example 1:

Input: root = [1,null,3,2,4,null,5,6]
Output: 3
Example 2:

Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: 5
Constraints:

The total number of nodes is in the range [0, 104].
The depth of the n-ary tree is less than or equal to 1000.

思路一:递归遍历每个子节点,取最大深度的子节点

    public int maxDepth(Node root) {
        if (root == null) {
            return 0;
        }

        int max = 0;
        for (Node child : root.children) {
            max = Math.max(max, maxDepth(child));
        }

        return max + 1;
    }

标签:559,max,depth,easy,ary,null,root,leetcode
From: https://www.cnblogs.com/iyiluo/p/17064604.html

相关文章

  • leetcode-543-easy
    DiameterofBinaryTreeGiventherootofabinarytree,returnthelengthofthediameterofthetree.Thediameterofabinarytreeisthelengthofthelon......
  • leetcode-530-easy
    MinimumAbsoluteDifferenceinBSTGiventherootofaBinarySearchTree(BST),returntheminimumabsolutedifferencebetweenthevaluesofanytwodifferent......
  • leetcode-405-easy
    ConvertaNumbertoHexadecimalGivenanintegernum,returnastringrepresentingitshexadecimalrepresentation.Fornegativeintegers,two’scomplementmet......
  • leetcode-501-easy
    FindModeinBinarySearchTreeGiventherootofabinarysearchtree(BST)withduplicates,returnallthemode(s)(i.e.,themostfrequentlyoccurredelemen......
  • leetocde-374-easy
    GuessNumberHigherorLowerWeareplayingtheGuessGame.Thegameisasfollows:Ipickanumberfrom1ton.YouhavetoguesswhichnumberIpicked.Eve......
  • LeetCode最长回文子串(/dp)
    原题解题目约束解法解法一#include<iostream>#include<string>#include<vector>usingnamespacestd;classSolution{public:stringlongestPa......
  • LeetCode_单周赛_329
    2544.交替数字和代码1转成字符串,逐个判断classSolution{publicintalternateDigitSum(intn){char[]s=(""+n).toCharArray();intt......
  • 【队列】LeetCode 281. 锯齿迭代器
    题目链接281.锯齿迭代器思路使用队列进行保存代码publicclassZigzagIterator{Queue<Iterator<Integer>>queue=newLinkedList<>();publicZigzagIt......
  • 【队列】LeetCode 346. 数据流中的移动平均值
    题目链接346.数据流中的移动平均值思路队列设计基础题代码classMovingAverage{privateIntegercurrentSum=0;privateQueue<Integer>queue=newLi......
  • [LeetCode] 684. Redundant Connection
    Inthisproblem,atreeisan undirectedgraph thatisconnectedandhasnocycles.Youaregivenagraphthatstartedasatreewith n nodeslabeledfrom......