|
| 1 | +# time complexity: O(n) |
| 2 | +# space complexity: O(n) |
| 3 | +from typing import List |
| 4 | + |
| 5 | + |
| 6 | +class TreeNode: |
| 7 | + def __init__(self, val=0, left=None, right=None): |
| 8 | + self.val = val |
| 9 | + self.left = left |
| 10 | + self.right = right |
| 11 | + |
| 12 | + |
| 13 | +class Solution: |
| 14 | + def getDirections( |
| 15 | + self, root: TreeNode, startValue: int, destValue: int |
| 16 | + ) -> str: |
| 17 | + lowestCommonAncestor = self.findLCA(root, startValue, destValue) |
| 18 | + pathToStart = [] |
| 19 | + pathToDest = [] |
| 20 | + self.findPath(lowestCommonAncestor, startValue, pathToStart) |
| 21 | + self.findPath(lowestCommonAncestor, destValue, pathToDest) |
| 22 | + directions = [] |
| 23 | + directions.extend("U" * len(pathToStart)) |
| 24 | + directions.extend(pathToDest) |
| 25 | + |
| 26 | + return "".join(directions) |
| 27 | + |
| 28 | + def findLCA( |
| 29 | + self, node: TreeNode, value1: int, value2: int |
| 30 | + ) -> TreeNode: |
| 31 | + if node is None: |
| 32 | + return None |
| 33 | + if node.val == value1 or node.val == value2: |
| 34 | + return node |
| 35 | + leftLCA = self.findLCA(node.left, value1, value2) |
| 36 | + rightLCA = self.findLCA(node.right, value1, value2) |
| 37 | + if leftLCA is None: |
| 38 | + return rightLCA |
| 39 | + elif rightLCA is None: |
| 40 | + return leftLCA |
| 41 | + else: |
| 42 | + return node |
| 43 | + |
| 44 | + def findPath( |
| 45 | + self, node: TreeNode, targetValue: int, path: List[str] |
| 46 | + ) -> bool: |
| 47 | + if node is None: |
| 48 | + return False |
| 49 | + if node.val == targetValue: |
| 50 | + return True |
| 51 | + path.append("L") |
| 52 | + if self.findPath(node.left, targetValue, path): |
| 53 | + return True |
| 54 | + path.pop() |
| 55 | + path.append("R") |
| 56 | + if self.findPath(node.right, targetValue, path): |
| 57 | + return True |
| 58 | + path.pop() |
| 59 | + return False |
| 60 | + |
| 61 | + |
| 62 | +startValue = 3 |
| 63 | +destValue = 6 |
| 64 | +root = TreeNode(5) |
| 65 | +root.left = TreeNode(1) |
| 66 | +root.left.left = TreeNode(3) |
| 67 | +root.right = TreeNode(2) |
| 68 | +root.right.left = TreeNode(6) |
| 69 | +root.right.right = TreeNode(4) |
| 70 | + |
| 71 | +print(Solution().getDirections(root, startValue, destValue)) |
0 commit comments