leetcode 235 binary search tree common ancestor

leetcode 235 binary search tree common ancestor

Subject description:

Given a binary search tree, find the nearest common ancestor of the two specified nodes of the tree. Baidu Encyclopedia recent common ancestor as defined: "For two nodes of the root of the tree T p, q, is represented as a common ancestor node x, that x is p, q ancestor depth as large as possible and x (a node can be its own ancestors).

Solution one: his writing, stupid thief

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        def findPath(root,num,tmp,path):
            if not root:
                return
            if root.val == num.val:
                path.append(tmp + [root])
                return
            findPath(root.left,num,tmp+[root],path)
            findPath(root.right,num,tmp+[root],path)
        minn = min(p.val, q.val)
        maxn = max(p.val, q.val)
        p_path = []
        q_path = []
        findPath(root,p,[],p_path)
        findPath(root,q,[],q_path)
        p_path = p_path[0]#[::-1]
        q_path = q_path[0]#[::-1]
        lenm = min(len(p_path),len(q_path))
        for i in range(0,lenm):
            if p_path[i].val == q_path[i].val:
                res = p_path[i]
        return res

Online wording

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        min_ = min(p.val,q.val)
        max_ = max(p.val,q.val)
        if not root:
            return 
        if min_ <= root.val <= max_:
            return root
        else:
            l = self.lowestCommonAncestor(root.left, p, q)
            r = self.lowestCommonAncestor(root.right, p, q)
            if l:
                return l
            if r:
                return r

Guess you like

Origin www.cnblogs.com/curtisxiao/p/11247858.html