您的位置:首页 > 编程语言 > Python开发

leetcode之 Lowest Common Ancestor of a Binary Tree

2016-01-12 01:28 459 查看
这题是跟Lowest Common Ancestor of a Binary Search Tree相似的思路,不过不再是直接通过比较值来判定,而是要通过看在中序排序中的位置来定。极端的情况比如单链形式的q,p只相差1的情况会非常慢。特意加上了相差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 __init__(self):
self.list1 = []
def inorder(self,root):
if root.left:
self.inorder(root.left)
self.list1.append(root)
if root.right:
self.inorder(root.right)
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
self.inorder(root)
self.indexofroot = self.list1.index(root)
self.indexofp = self.list1.index(p)
self.indexofq = self.list1.index(q)

def ancestor(root, p, q):
if self.indexofq <= self.indexofroot <= self.indexofp or self.indexofq >= self.indexofroot >= self.indexofp:
return root
if abs(self.indexofp - self.indexofq) == 1:
if p.left == q or p.right == q:
return p
else:
return p
elif self.indexofroot < self.indexofp and self.indexofroot < self.indexofq:
self.indexofroot = self.list1.index(root.right)
return ancestor(root.right, p, q)
else:
self.indexofroot = self.list1.index(root.left)
return ancestor(root.left, p, q)
return ancestor(root, p, q)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息