leetcode 235バイナリ検索ツリーの共通の祖先
件名の説明:
二分探索木を考えると、ツリーの指定された2つのノードの最も近い共通の祖先を見つけます。Baiduの百科事典定義されるような最近の共通の祖先「ツリーT pのルートの二つのノードについては、qは、共通の祖先ノードXとして表され、そのXはP、Qの祖先の深さが可能であり、xと同じ大きさであります(ノードは、それ自身の祖先であることができます)。
解決策1:彼の文章、愚かな泥棒
# 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
オンライン言葉遣い
# 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