LeetCode 1522. Diameter of N-Ary Tree(递归)
文章目錄
- 1. 題目
- 2. 解題
1. 題目
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:
Example 2:
Example 3:
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/diameter-of-n-ary-tree
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
/* // Definition for a Node. class Node { public:int val;vector<Node*> children;Node() {}Node(int _val) {val = _val;}Node(int _val, vector<Node*> _children) {val = _val;children = _children;} }; */class Solution {int ans = 0; public:int diameter(Node* root) {h(root);return ans;}int h(Node* root){if(!root) return 0;int maxdep1 = 0, maxdep2 = 0, height;for(auto c : root->children){height = h(c);if(height >= maxdep1){maxdep2 = maxdep1;maxdep1 = height;}else if(height > maxdep2)maxdep2 = height;}ans = max(ans, maxdep2+maxdep1);return max(maxdep1, maxdep2) + 1;} };32 ms 10.7 MB
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 1522. Diameter of N-Ary Tree(递归)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 1610. 可见点的最
- 下一篇: LeetCode MySQL 569.