【发布时间】:2017-08-05 16:21:46
【问题描述】:
这是一个常见的算法问题。我试图在二叉搜索树中找到中序后继。这是我的代码
def inorderSuccessor(self, root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
"""
# if Node has a right child, go all the way down
if p.right:
curr = p
while curr.left:
curr = curr.left
return curr
# first ancestor whose left child the node is
ans = None
curr = root
while curr is not p:
if curr.val < p.val:
curr = curr.right
else:
ans = curr
curr = curr.left
return ans
问题是当 p 是树中的最高节点时,这不起作用。我一直在为如何让这个边缘案例运转而摸不着头脑。
【问题讨论】:
-
你是不是要实现中序树遍历?
-
Nope 中序遍历的复杂度为 O(n)。假设树是平衡的,我试图找到 O(log n) 复杂度的有序后继。
-
您的意见是什么?您的实际/预期输出是多少?添加这些帮助。
-
在
if p.right之后你设置了curr = p但你真的想要curr = p.right。