본문 바로가기
Leetcode

[LeetCode] Lowest Common Ancestor 파이썬 (tree)

by YGSEO 2021. 4. 7.
728x90
class Solution:
    # @param {TreeNode} root
    # @param {TreeNode} p
    # @param {TreeNode} q
    # @return {TreeNode}
    def lowestCommonAncestor(self, root, p, q):
        s, b = sorted([p.val, q.val])
        while not s <= root.val <= b:
            # Keep searching since root is outside of [s, b].
            root = root.left if s <= root.val else root.right
        # s <= root.val <= b.
        return root

 

출처: github.com/jiapengwen/LeetCode/blob/master/Python/lowest-common-ancestor-of-a-binary-search-tree.py

728x90

댓글