In order traversal Solution

  • 0
    class Solution(object):
        def lowestCommonAncestor(self, root, p, q):
            dic = dict()
            in_order = []
            self.traverse(root, in_order)
            for i in range(len(in_order)):
                dic[in_order[i]] = i
            while root:
                if root == p or root == q:
                    return root
                if dic[p] < dic[root] < dic[q] or dic[q] < dic[root] < dic[p]:
                    return root
                if dic[p] < dic[root] and dic[q] < dic[root]:
                    root = root.left
                    root = root.right
            return root
        def traverse(self, root, arr):
            if not root:
            self.traverse(root.left, arr)
            self.traverse(root.right, arr)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.