Leetcode 285. Inorder Successor in BST
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
本题要求查找p在树中的inorder successor(中序遍历时的下一个节点)。根据p和root的关系,有三种情况。
1. p在root的左子树中: 1.1 p在左子树中的successor不为空,那么输出这个successor
1.2 p在左子树中的successor为空,那么p的successor就是root
2. p在root的右子树中: root和左子树中的node显然都在p之前,所以p的successor就是p在右子树中的successor.
1 class Solution(object): 2 def inorderSuccessor(self, root, p): 3 """ 4 :type root: TreeNode 5 :type p: TreeNode 6 :rtype: TreeNode 7 """ 8 if not root: 9 return None 10 if p.val < root.val: 11 ls = self.inorderSuccessor(root.left, p) 12 if ls == None: 13 return root 14 else: 15 return ls 16 else: 17 return self.inorderSuccessor(root.right, p)

浙公网安备 33010602011771号