|
| 1 | +# Time: O(n) |
| 2 | +# Space: O(h) |
| 3 | + |
| 4 | +# Definition for a binary tree node. |
| 5 | +class TreeNode(object): |
| 6 | + def __init__(self, x): |
| 7 | + pass |
| 8 | + |
| 9 | + |
| 10 | +class Solution(object): |
| 11 | + def lowestCommonAncestor(self, root, p, q): |
| 12 | + """ |
| 13 | + :type root: TreeNode |
| 14 | + :type p: TreeNode |
| 15 | + :type q: TreeNode |
| 16 | + :rtype: TreeNode |
| 17 | + """ |
| 18 | + def iter_dfs(node, p, q): |
| 19 | + result = None |
| 20 | + stk = [(1, (node, [0]))] |
| 21 | + while stk: |
| 22 | + step, params = stk.pop() |
| 23 | + if step == 1: |
| 24 | + node, ret = params |
| 25 | + if not node: |
| 26 | + continue |
| 27 | + ret1, ret2 = [0], [0] |
| 28 | + stk.append((2, (node, ret1, ret2, ret))) |
| 29 | + stk.append((1, (node.right, ret2))) |
| 30 | + stk.append((1, (node.left, ret1))) |
| 31 | + elif step == 2: |
| 32 | + node, ret1, ret2, ret = params |
| 33 | + curr = int(node == p or node == q) |
| 34 | + if curr+ret1[0]+ret2[0] == 2 and not result: |
| 35 | + result = node |
| 36 | + ret[0] = curr+ret1[0]+ret2[0] |
| 37 | + return result |
| 38 | + |
| 39 | + return iter_dfs(root, p, q) |
| 40 | + |
| 41 | + |
| 42 | +# Time: O(n) |
| 43 | +# Space: O(h) |
| 44 | +class Solution2(object): |
| 45 | + def lowestCommonAncestor(self, root, p, q): |
| 46 | + """ |
| 47 | + :type root: TreeNode |
| 48 | + :type p: TreeNode |
| 49 | + :type q: TreeNode |
| 50 | + :rtype: TreeNode |
| 51 | + """ |
| 52 | + def dfs(node, p, q, result): |
| 53 | + if not node: |
| 54 | + return 0 |
| 55 | + left = dfs(node.left, p, q, result) |
| 56 | + right = dfs(node.right, p, q, result) |
| 57 | + curr = int(node == p or node == q) |
| 58 | + if curr+left+right == 2 and not result[0]: |
| 59 | + result[0] = node |
| 60 | + return curr+left+right |
| 61 | + |
| 62 | + result = [0] |
| 63 | + dfs(root, p, q, result) |
| 64 | + return result[0] |
| 65 | + |
0 commit comments