|
| 1 | +/** |
| 2 | + * Question Link: https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/ |
| 3 | + * Primary idea: The shortest path should pass LCA. Find paths for two nodes and remove their longgest common prefix. |
| 4 | + * Time Complexity: O(n), Space Complexity: O(n) |
| 5 | + * |
| 6 | + * Definition for a binary tree node. |
| 7 | + * public class TreeNode { |
| 8 | + * public var val: Int |
| 9 | + * public var left: TreeNode? |
| 10 | + * public var right: TreeNode? |
| 11 | + * public init(_ val: Int) { |
| 12 | + * self.val = val |
| 13 | + * self.left = nil |
| 14 | + * self.right = nil |
| 15 | + * } |
| 16 | + * } |
| 17 | + */ |
| 18 | + |
| 19 | +class StepByStepDirectionsBinaryTreeNode { |
| 20 | + func getDirections(_ root: TreeNode?, _ startValue: Int, _ destValue: Int) -> String { |
| 21 | + guard let root = root else { |
| 22 | + return "" |
| 23 | + } |
| 24 | + |
| 25 | + let startPath = getPath(root, startValue) |
| 26 | + let destPath = getPath(root, destValue) |
| 27 | + let len = longestCommonPrefixLen(startPath, destPath) |
| 28 | + |
| 29 | + return String(repeating: "U", count: startPath.count - len) + destPath.dropFirst(len) |
| 30 | + } |
| 31 | + |
| 32 | + private func longestCommonPrefixLen(_ s: String, _ d: String) -> Int { |
| 33 | + var i = 0 |
| 34 | + let s = Array(s), d = Array(d) |
| 35 | + |
| 36 | + while i < min(s.count, d.count) { |
| 37 | + if s[i] != d[i] { |
| 38 | + break |
| 39 | + } |
| 40 | + |
| 41 | + i += 1 |
| 42 | + } |
| 43 | + |
| 44 | + return i |
| 45 | + } |
| 46 | + |
| 47 | + private func getPath(_ parent: TreeNode, _ val: Int) -> String { |
| 48 | + var queue = [(parent, "")] |
| 49 | + |
| 50 | + while !queue.isEmpty { |
| 51 | + let current = queue.removeFirst() |
| 52 | + |
| 53 | + if current.0.val == val { |
| 54 | + return current.1 |
| 55 | + } |
| 56 | + |
| 57 | + if let left = current.0.left { |
| 58 | + queue.append((left, current.1 + "L")) |
| 59 | + } |
| 60 | + if let right = current.0.right { |
| 61 | + queue.append((right, current.1 + "R")) |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return "" |
| 66 | + } |
| 67 | +} |
0 commit comments