|
| 1 | +# Time: O(n) |
| 2 | +# Space: O(h) |
| 3 | + |
| 4 | +# tree, dfs |
| 5 | +class Solution(object): |
| 6 | + def longestPath(self, parent, s): |
| 7 | + """ |
| 8 | + :type parent: List[int] |
| 9 | + :type s: str |
| 10 | + :rtype: int |
| 11 | + """ |
| 12 | + def iter_dfs(s, adj): |
| 13 | + result = 0 |
| 14 | + stk = [(1, (0, [0]))] |
| 15 | + while stk: |
| 16 | + step, args = stk.pop() |
| 17 | + if step == 1: |
| 18 | + u, ret = args |
| 19 | + top2 = [0]*2 |
| 20 | + stk.append((4, (top2, ret))) |
| 21 | + stk.append((2, (u, 0, top2, ret))) |
| 22 | + elif step == 2: |
| 23 | + u, i, top2, ret = args |
| 24 | + if i == len(adj[u]): |
| 25 | + continue |
| 26 | + ret2 = [0] |
| 27 | + stk.append((3, (u, i, top2, ret2))) |
| 28 | + stk.append((1, (adj[u][i], ret2))) |
| 29 | + elif step == 3: |
| 30 | + u, i, top2, ret2 = args |
| 31 | + if s[adj[u][i]] != s[u]: |
| 32 | + if ret2[0] > top2[0]: |
| 33 | + top2[0], top2[1] = ret2[0], top2[0] |
| 34 | + elif ret2[0] > top2[1]: |
| 35 | + top2[1] = ret2[0] |
| 36 | + stk.append((2, (u, i+1, top2, ret))) |
| 37 | + elif step == 4: |
| 38 | + top2, ret = args |
| 39 | + result = max(result, top2[0]+top2[1]+1) |
| 40 | + ret[0] = top2[0]+1 |
| 41 | + return result |
| 42 | + |
| 43 | + |
| 44 | + adj = [[] for _ in xrange(len(s))] |
| 45 | + for i in xrange(1, len(parent)): |
| 46 | + adj[parent[i]].append(i) |
| 47 | + return iter_dfs(s, adj) |
| 48 | + |
| 49 | + |
| 50 | +# Time: O(n) |
| 51 | +# Space: O(h) |
| 52 | +# tree, dfs |
| 53 | +class Solution2(object): |
| 54 | + def longestPath(self, parent, s): |
| 55 | + """ |
| 56 | + :type parent: List[int] |
| 57 | + :type s: str |
| 58 | + :rtype: int |
| 59 | + """ |
| 60 | + def dfs(s, adj, u, result): |
| 61 | + top2 = [0]*2 |
| 62 | + for v in adj[u]: |
| 63 | + l = dfs(s, adj, v, result) |
| 64 | + if s[v] == s[u]: |
| 65 | + continue |
| 66 | + if l > top2[0]: |
| 67 | + top2[0], top2[1] = l, top2[0] |
| 68 | + elif l > top2[1]: |
| 69 | + top2[1] = l |
| 70 | + result[0] = max(result[0], top2[0]+top2[1]+1) |
| 71 | + return top2[0]+1 |
| 72 | + |
| 73 | + |
| 74 | + adj = [[] for _ in xrange(len(s))] |
| 75 | + for i in xrange(1, len(parent)): |
| 76 | + adj[parent[i]].append(i) |
| 77 | + result = [0] |
| 78 | + dfs(s, adj, 0, result) |
| 79 | + return result[0] |
| 80 | + |
0 commit comments