|
| 1 | +// My initial solution. 37 / 38 test cases passed. https://tinyurl.com/y2wfypuh |
| 2 | +class Solution { |
| 3 | + func diameter(_ root: Node?) -> Int { |
| 4 | + guard let root = root else { |
| 5 | + return 0 |
| 6 | + } |
| 7 | + var (excludingThisNode, asRoot, asBranch) = diameterDFSHelper(root) |
| 8 | + return [excludingThisNode, asRoot, asBranch].max()! |
| 9 | + } |
| 10 | + |
| 11 | + func diameterDFSHelper(_ root: Node) -> (Int, Int, Int) { |
| 12 | + guard !root.children.isEmpty else { |
| 13 | + return (0, 0, 0) |
| 14 | + } |
| 15 | + |
| 16 | + var (excludingThisNode, max1, max2) = (0, 0, 0) |
| 17 | + for node in root.children { |
| 18 | + let (_, asRootCurr, asBranchCurr) = diameterDFSHelper(node) |
| 19 | + excludingThisNode = max(excludingThisNode, asRootCurr) |
| 20 | + if asBranchCurr > max1 { |
| 21 | + max2 = max1 |
| 22 | + max1 = asBranchCurr |
| 23 | + } else if asBranchCurr > max2 { |
| 24 | + max2 = asBranchCurr |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + if root.children.count == 1 { |
| 29 | + return (excludingThisNode, 1 + max1, 1 + max1) |
| 30 | + } else { |
| 31 | + return (excludingThisNode, 2 + max1 + max2, 1 + max1) |
| 32 | + } |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +// https://tinyurl.com/y5oyyjpf |
| 37 | +class Solution { |
| 38 | + var result = 0 |
| 39 | + func diameter(_ root: Node?) -> Int { |
| 40 | + guard let root = root else { return 0 } |
| 41 | + getHeightDFSHelper(root) |
| 42 | + return result |
| 43 | + } |
| 44 | + |
| 45 | + func getHeightDFSHelper(_ root: Node?) -> Int { |
| 46 | + guard let root = root else { return 0 } |
| 47 | + var max1Height = 0 |
| 48 | + var max2Height = 0 |
| 49 | + for child in root.children { |
| 50 | + let currentHeight = getHeightDFSHelper(child) |
| 51 | + if currentHeight > max1Height { |
| 52 | + max2Height = max1Height |
| 53 | + max1Height = currentHeight |
| 54 | + } else if currentHeight > max2Height { |
| 55 | + max2Height = currentHeight |
| 56 | + } |
| 57 | + } |
| 58 | + result = max(result, max1Height + max2Height) |
| 59 | + return max(max1Height, max2Height) + 1 |
| 60 | + } |
| 61 | +} |
0 commit comments