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)
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法