leetcode之 Lowest Common Ancestor of a Binary Tree
来源:互联网 发布:第三波软件 编辑:程序博客网 时间:2024/06/02 04:58
这题是跟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 = Noneclass 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)
0 0
- LeetCode OJ 之 Lowest Common Ancestor of a Binary Tree
- LeetCode 之 Lowest Common Ancestor of a Binary Search Tree
- leetcode之Lowest Common Ancestor of a Binary Search Tree
- leetcode之 Lowest Common Ancestor of a Binary Tree
- leetcode之Lowest Common Ancestor of a Binary Search Tree
- leetcode之Lowest Common Ancestor of a Binary Search Tree
- leetcode之Lowest Common Ancestor of a Binary Search Tree
- Leetcode 之 Lowest Common Ancestor of a Binary Search Tree
- leetcode 235: Lowest Common Ancestor of a Binary Search Tree
- leetcode - Lowest Common Ancestor of a Binary Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- leetcode: Lowest Common Ancestor of a Binary Search Tree
- [leetcode][dfs] Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235.Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 236.Lowest Common Ancestor of a Binary Tree
- [LeetCode]236.Lowest Common Ancestor of a Binary Tree
- 【LeetCode】235 Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】236 Lowest Common Ancestor of a Binary Tree
- /bin/bash^M: bad interpreter: No such file or dire
- 自己动手用C++写的图像处理软件(不调用外部包)
- [看书日记20160112]Binder
- 使用ImageLoader第三方框架,加载网络图片
- POJ-2965-The Pilots Brothers' refrigerator-bfs枚举-位运算
- leetcode之 Lowest Common Ancestor of a Binary Tree
- nginx+tomcat集群
- QTGraphicsViewFramework学习
- cf-edu#5-C The Labyrinth-dfs记忆化搜搜
- 深入了解JAVA可变长度的参数(Varargs)
- Android中 Window 、WindowManager、WindowManager.LayoutParams 相关内容
- Cocos2dX笔记1——生成Docs
- cf-edu#5-D - Longest k-Good Segment-map+贪心维护
- 为PopupWindow设置动画效果