Given the root
of a binary search tree and a node p
in it, return the in-order successor of that node in the BST. If the given node has no in-order successor in the tree, return null
.
The successor of a node p
is the node with the smallest key greater than p.val
.
Example 1:
Input: root = [2,1,3], p = 1 Output: 2 Explanation: 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type.
Example 2:
Input: root = [5,3,6,2,4,null,null,1], p = 6
Output: null
Explanation: There is no in-order successor of the current node, so the answer is null
.
Constraints:
- The number of nodes in the tree is in the range
[1, 104]
. -105 <= Node.val <= 105
- All Nodes will have unique values.
题目给定一个二叉搜索树的根节点root和树中的某一个节点p,要求出节点p的中序遍历的后继Successor,所谓后继就是树所有值大于p节点值的节点中值最小的那个节点。如果后继不存在就返回空节点。
二叉搜索树的中序遍历的节点是有序的,因此最直接的解法就是中序遍历整棵树,当遇到节点p时,如果遍历还没结束,那么p的下一个节点就是p的后继节点。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'Optional[TreeNode]':
def inorder(node):
nonlocal res, found
if not node:
return
inorder(node.left)
if node == p:
found = True
elif found and not res:
res = node
return
inorder(node.right)
res, found = None, False
inorder(root)
return res
以上解法是利用了二叉搜索树中序遍历的特点,最坏情况就是p是最后一个节点,因此需要遍历所有节点,时间复杂度O(n)。通常关于二叉搜索树查找的题都是可以做到O(logn),这样题同样有更优解。
我们在学校学习二叉搜索树和后继节点时就知道一个节点的后继节点有两种情况:
1)如果当前节点存在右子树,那么它的后继节点就是右子树中最左边的那个节点。
2)如果当前节点不存在右子树,那么它的后继节点就是它所有父节点中的其中一个(当然也有可能不存在后继节点)。从当前节点开始顺着父节点直到根节点,当遇到一个节点是其父节点的左子节点时那么该父节点就是p的后继节点。要是一直到根节点还没遇到就说明后继不存在。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'Optional[TreeNode]':
if p.right:
res = p.right
while res.left:
res = res.left
return res
def search(cur):
if not cur or cur == p:
return
nonlocal res
if p.val < cur.val:
search(cur.left)
if not res:
res = cur
elif p.val > cur.val:
search(cur.right)
res = None
search(root)
return res