1522. Diameter of N-Ary Tree

This is a similar problem with "543. Diameter of Binary Tree", the only difference is 543 is a binary tree, and 1522 is an n_ary tree.

For 1522, we need to get the two longest path passing through the node, following is the solution:

    private int res = 0;
    public int diameter(Node root) {
        helper(root);
        return res;
    }
    
    private int helper(Node root){
        if(root.children==null)
            return 0;
        int max1 = 0, max2 = 0;
        List<Node> children = root.children;
        for(Node child: children){
            int len = helper(child)+1;
            if(len>max1){      //find the longest two paths
                max2 = max1;     
                max1 = len;
            }else if(len>max2){
                max2 = len;
            }
        }
        res = Math.max(res, max1+max2);
        return max1;
    }
上一篇:pygame小游戏开发 - 俄罗斯方块


下一篇:Python | 分析txt文档特定词汇的词频,以《天龙八部》为例