"""# Definition for a Node.class Node: def __init__(self, val=None, children=None): self.val = val self.children = children if children is not None else []"""classSolution:defdiameter(self,root:'Node')->int:""" :type root: 'Node' :rtype: int """defdfs(root):ifrootisNone:return0nonlocalansm1=m2=0forchildinroot.children:t=dfs(child)ift>m1:m2,m1=m1,telift>m2:m2=tans=max(ans,m1+m2)return1+m1ans=0dfs(root)returnans
/*// Definition for a Node.class Node { public int val; public List<Node> children; public Node() { children = new ArrayList<Node>(); } public Node(int _val) { val = _val; children = new ArrayList<Node>(); } public Node(int _val,ArrayList<Node> _children) { val = _val; children = _children; }};*/classSolution{privateintans;publicintdiameter(Noderoot){ans=0;dfs(root);returnans;}privateintdfs(Noderoot){if(root==null){return0;}intm1=0,m2=0;for(Nodechild:root.children){intt=dfs(child);if(t>m1){m2=m1;m1=t;}elseif(t>m2){m2=t;}}ans=Math.max(ans,m1+m2);return1+m1;}}
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */funcdiameter(root*Node)int{ans:=0vardfsfunc(root*Node)intdfs=func(root*Node)int{ifroot==nil{return0}m1,m2:=0,0for_,child:=