|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * type TreeNode struct { |
| 4 | + * Val int |
| 5 | + * Left *TreeNode |
| 6 | + * Right *TreeNode |
| 7 | + * } |
| 8 | + */ |
| 9 | +func getDirections(root *TreeNode, startValue int, destValue int) string { |
| 10 | + var lca func(node *TreeNode, p, q int) *TreeNode |
| 11 | + lca = func(node *TreeNode, p, q int) *TreeNode { |
| 12 | + if node == nil || node.Val == p || node.Val == q { |
| 13 | + return node |
| 14 | + } |
| 15 | + left := lca(node.Left, p, q) |
| 16 | + right := lca(node.Right, p, q) |
| 17 | + if left != nil && right != nil { |
| 18 | + return node |
| 19 | + } |
| 20 | + if left != nil { |
| 21 | + return left |
| 22 | + } |
| 23 | + return right |
| 24 | + } |
| 25 | + var dfs func(node *TreeNode, x int, path *[]byte) bool |
| 26 | + dfs = func(node *TreeNode, x int, path *[]byte) bool { |
| 27 | + if node == nil { |
| 28 | + return false |
| 29 | + } |
| 30 | + if node.Val == x { |
| 31 | + return true |
| 32 | + } |
| 33 | + *path = append(*path, 'L') |
| 34 | + if dfs(node.Left, x, path) { |
| 35 | + return true |
| 36 | + } |
| 37 | + (*path)[len(*path)-1] = 'R' |
| 38 | + if dfs(node.Right, x, path) { |
| 39 | + return true |
| 40 | + } |
| 41 | + *path = (*path)[:len(*path)-1] |
| 42 | + return false |
| 43 | + } |
| 44 | + |
| 45 | + node := lca(root, startValue, destValue) |
| 46 | + pathToStart := []byte{} |
| 47 | + pathToDest := []byte{} |
| 48 | + dfs(node, startValue, &pathToStart) |
| 49 | + dfs(node, destValue, &pathToDest) |
| 50 | + return string(bytes.Repeat([]byte{'U'}, len(pathToStart))) + string(pathToDest) |
| 51 | +} |
0 commit comments