We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 61ea902 commit e8d233fCopy full SHA for e8d233f
1245-tree-diameter.js
@@ -0,0 +1,38 @@
1
+/**
2
+ * @param {number[][]} edges
3
+ * @return {number}
4
+ */
5
+const treeDiameter = function (edges) {
6
+ const graph = {}
7
+ for (const [u, v] of edges) {
8
+ if (graph[u] == null) graph[u] = new Set()
9
+ if (graph[v] == null) graph[v] = new Set()
10
+ graph[u].add(v)
11
+ graph[v].add(u)
12
+ }
13
+
14
+ let res = 0
15
16
+ dfs(0, -1)
17
18
+ return res
19
20
+ function dfs(node, parent) {
21
+ let first = 0, sec = 0
22
23
+ for(const nxt of (graph[node] || [])) {
24
+ if(nxt === parent) continue
25
+ const childNum = dfs(nxt, node)
26
+ if(childNum > first) {
27
+ sec = first
28
+ first = childNum
29
+ } else if(childNum > sec){
30
+ sec = childNum
31
32
33
34
+ const nodeNum = first + sec + 1
35
+ res = Math.max(res, nodeNum - 1)
36
+ return first + 1
37
38
+}
0 commit comments