@author = YHR | 转载请标明来源!
题目描述
先马一下,太困了,睡觉了!
代码
class treenode:
def __init__(self, val, left=None, right=None, parent=None):
self.val = val
self.left = left
self.right = right
self.parent = parent
# 剑指offer08
def find(p):
if p is None:
return None
elif p.right is not None:
# 1. 首先判断是否有右节点
next = p.right
while next.left is not None:
next = next.left
return next
else:
# 2. 没有右节点
# 2.1 判断自己是否是父节点的左节点,如果是的话,下一个就是父节点
parent = p.parent
if parent is None:
return parent
elif parent.left is p:
return parent
else:
# 2.2 自己是父节点的右孩子
# 找到父辈,是父辈的父辈的左孩子为止
this = parent
while this.parent is not None and this.parent.left is not this:
this = this.parent
return this.parent