[LeetCode] 1522. Diameter of N-Ary Tree

Given a root of an N-ary tree, you need to compute the length of the diameter of the tree.

The diameter of an N-ary tree is the length of the longest path between any two nodes in the tree. This path may or may not pass through the root.

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

Example 1:

Input: root = [1,null,3,2,4,null,5,6]
Output: 3
Explanation: Diameter is shown in red color.

Example 2:

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

Example 3:

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: 7

Constraints:

  • The depth of the n-ary tree is less than or equal to 1000.
  • The total number of nodes is between [1, 104].

N 叉树的直径。

给定一棵 N 叉树的根节点 root ,计算这棵树的直径长度。

N 叉树的直径指的是树中任意两个节点间路径中 最长 路径的长度。这条路径可能经过根节点,也可能不经过根节点。

(N 叉树的输入序列以层序遍历的形式给出,每组子节点用 null 分隔)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diameter-of-n-ary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是DFS后序遍历。这道题要找的直径长度跟543题类似,也是找树中两条最长的路径和,只不过这道题给的是一个多叉树。既然是多叉树中找两条最长的路径,我们要在过程中一直记录最长的两条子树的长度。往父节点返回的是最长的子树路径 + 1。这道题还是注意最后所求的东西和helper函数返回的东西的区别。

时间O(n)

空间O(n)

Java实现

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4     public int val;
 5     public List<Node> children;
 6 
 7     
 8     public Node() {
 9         children = new ArrayList<Node>();
10     }
11     
12     public Node(int _val) {
13         val = _val;
14         children = new ArrayList<Node>();
15     }
16     
17     public Node(int _val,ArrayList<Node> _children) {
18         val = _val;
19         children = _children;
20     }
21 };
22 */
23 
24 class Solution {
25     int res = 0;
26 
27     public int diameter(Node root) {
28         helper(root);
29         return res;
30     }
31 
32     private int helper(Node root) {
33         if (root == null) {
34             return 0;
35         }
36         List<Node> children = root.children;
37         int first = 0;
38         int second = 0;
39         for (Node child : children) {
40             int res = helper(child);
41             if (res > first) {
42                 second = first;
43                 first = res;
44             } else if (res > second) {
45                 second = res;
46             }
47         }
48         res = Math.max(res, first + second);
49         return first + 1;
50     }
51 }

 

相关题目

104. Maximum Depth of Binary Tree

110. Balanced Binary Tree

366. Find Leaves of Binary Tree

543. Diameter of Binary Tree

1522. Diameter of N-Ary Tree

LeetCode 题目总结

posted @ 2021-01-30 16:22  CNoodle  阅读(759)  评论(0编辑  收藏  举报