# 节点最长距离
function findLongest(root) {
if (!root) {
return 0
}
const leftDepth = getDepth(root.left)
const rightDepth = getDepth(root.right)
const leftLongest = findLongest(root.left)
const rightLongest = findLongest(root.right)
return Math.max(leftDepth + rightDepth + 1, leftLongest, rightLongest)
}
function getDepth(node) {
if (!node) {
return 0
}
const left = getDepth(node.left)
const right = getDepth(node.right)
return Math.max(left, right) + 1
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23