/**
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/
// 没什么意义,直接每个节点取子节点前2大深度之和的最大值即可
// 深度通过叶子反向累计
func diameter(root *Node) int {
var ans int
var helper func(node *Node) int
helper = func(node *Node) int{
if node==nil{
return 0
}
var v1,v2 int
for _,c := range node.Children{
d := helper(c)
if d>=v1{
v1,v2 = d,v1
}else if d>v2{
v2 = d
}
}
if v := v1+v2; v>ans{
ans = v
}
return v1+1
}
helper(root)
return ans
}
/*
// 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;
}
};
*/
class Solution {
int ans;
public int diameter(Node root) {
postSearch(root);
return ans;
}
public int postSearch(Node node){
if(node.children.size() == 0){
return 0;
}
int v1 = 0, v2 = 0;
for(Node ch : node.children){
int t = postSearch(ch) + 1;
if(t >= v1){
v2 = v1;
v1 = t;
}else if(t > v2){
v2 = t;
}
}
ans = Math.max(ans, v1 + v2);
return v1;
}
}
"""
# 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 []
"""
class Solution:
def diameter(self, root: 'Node') -> int:
"""
:type root: 'Node'
:rtype: int
"""
self.adjVex = defaultdict(list) #邻接表
self.dfs(root) #初始化邻接表,建图
que = [root] #随便选一个点作为起点
visited = set()
visited.add(root) #记忆化
cur = root #全局变量,记下第一次BFS的最后一个点
while que:
cur_len = len(que)
for _ in range(cur_len):
cur = que.pop(0)
for nxt in self.adjVex[cur]:
if nxt not in visited:
visited.add(nxt)
que.append(nxt)
visited.clear()
que = [cur] #第一次BFS最后一个点最为第二次BFS的起点
visited.add(cur) #记忆化
level = -1 #波纹法 记录距离
while que:
cur_len = len(que)
level += 1
for _ in range(cur_len): #波纹法
cur = que.pop(0)
for nxt in self.adjVex[cur]:
if nxt not in visited:
visited.add(nxt)
que.append(nxt)
return level
def dfs(self, rt: 'Node') -> None: #初始化邻接表,建图
if not rt:
return
for ch in rt.children:
self.adjVex[rt].append(ch)
self.adjVex[ch].append(rt)
self.dfs(ch)