首页 > 编程语言 >LeetCode-Java-559. Maximum Depth of N-ary Tree

LeetCode-Java-559. Maximum Depth of N-ary Tree

时间:2022-12-14 15:05:56浏览次数:49  
标签:Node 559 int ary Tree children tag root public


题目

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.

图在这

LeetCode-Java-559. Maximum Depth of N-ary Tree_i++

代码

通过递归的思想,对子节点进行不同的处理

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

public Node() {}

public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public int maxDepth(Node root) {
if(root == null){
return 0;
}else{
return deep(root,1);
}
}

public static int deep(Node root ,int d){
List<Node> childer = root.children;
int size=childer==null?0:childer.size();
if(size==0){
return d;
}else{
int [] tag = new int[size];
for(int i=0;i<size;i++){
Node x = childer.get(i);
tag[i] = deep(x,d+1);
}
int max = 0;
for(int i=0;i<size;i++){
if(tag[i]>tag[max]){
max = i;
}
}
return tag[max];
}
}
}


标签:Node,559,int,ary,Tree,children,tag,root,public
From: https://blog.51cto.com/u_12938555/5936980

相关文章

  • QTreewidget树状列表右击事件
     树状列表右击事件(添加删除修改等操作) 思路:首先我们需要一个voidcontextMenuEvent(QContextMenuEvent*event);管理Menu事件的一个接口此接口为系统自带的,不需......
  • linux环境变量LD_LIBRARY_PATH
    LD_LIBRARY_PATH是Linux系统下的环境变量名,类似于Path(设置可执行文件的搜索路径)。作用:用于指定查找共享库(动态链接库)时除了默认路径(./lib和./usr/lib)之外的其他路径。......
  • Missing boundary in multipart/form-data
    [13-Dec-202217:56:46Asia/Shanghai]PHPWarning:Missingboundaryinmultipart/form-dataPOSTdatainUnknownonline0最近在服务器中发现大量的Missingboun......
  • Java:Should I use a `HashSet` or a `TreeSet` for a very large dataset?
    这是StackOverflow上一个有意思的提问,记录一下。原地址在这翻译:对于大型数据集,应该使用”哈希集”还是”树集”?(因为HashTable有着O(1)的查找速度比树结构更有效率,虽然H......
  • Day1-English Diary
    Todaywehad4onlineclasses,whataterribleMonday.It'sevenworseformebecauseIwenttobedat2:00amlastnight.These4classesareindeed3courses:......
  • Antd (v3)在form中使用 treeSelect 选择后显示所有的父节点
    Antd(v3)在form中使用treeSelect选择后显示所有的父节点需求:constd=[{"children":[{"name":"1-1"},{"name":......
  • RobotFramework学习笔记:Robot Framework和BrowserLibrary(PlayWright)简介
    1为什么要开始写这个? 大家如果在测试学习交流群的话,就应该能感受到群里满满的学习氛围,近期呢,群里有一位大佬利用自己空闲的时间,准备录制一系列的自动化学习视频,目前会主要......
  • codeforces 596 div2 p-binary(数位复杂度压缩)
    题目大意:已知: 同时  ,问k最少为多少。解题思路:首先,我们看到这里有2的n次方,我们考虑能不能从二进制表示下手,我们通过移位来表示:得到公式 ,很直接的想法是我们让k从小到大......
  • tree
    1、led 2、pinctrl和gpio子系统  3、蜂鸣器  }4、按键  5、linux中断1、key{  6、linux自带led驱动  7、i2c   8、spi ......
  • TreeMap使用案例-多个映射(中级版)
    细节问题请看简单版publicclassWordMapn{publicstaticMap<String,List<String>>computeAdjacentWords(List<String>theWords){Map<String,L......