DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,503 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Miss Pooja Anilkumar Patel
Miss Pooja Anilkumar Patel

Posted on • Updated on

235. Leetcode solution in python3


class Solution:
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """

        # approach: compare current node with p and q, then move
        #           current to it’s left or right child by result

        current = root
        while root:
            if root.val > p.val and root.val > q.val:
                root = root.left
            elif root.val < p.val and root.val < q.val:
                root = root.right
            else: break

        return root
Enter fullscreen mode Exit fullscreen mode

leetcode

challenge

here is the link for the problem:
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.