1 class TreeNode: 2 def __init__(self, val=0, left=None, right=None, parent=None): 3 self.val = val 4 self.left = left 5 self.right = right 6 self.parent = parent 7 8 9 def get_left_most(node): 10 if not node: 11 return node 12 while node.left: 13 node = node.left 14 return node 15 16 def get_successor_node(node): 17 if not node: 18 return node 19 # 如果有右树,则为右子树中最左的节点 20 if node.right: 21 return get_left_most(node.right) 22 else: 23 parent = node.parent 24 # 当前节点是其父节点的右孩子,当前节点可能为最右节点 25 while not parent and parent.left != node: 26 node = parent 27 parent = node.parent 28 return parent