描述
给一个二叉树和节点p,保证p在二叉树内,求p的后继
思路
如果当前的root小于或等于p,返回右子树的结果。
否则,获取左子树的递归结果,如果结果为null,返回当前的root,否则返回递归结果。
"""
Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
class Solution:
"""
@param: root: The root of the BST.
@param: p: You need find the successor node of p.
@return: Successor of p.
"""
def inorderSuccessor(self, root, p):
# write your code here
if root == None:
return None
if root.val <= p.val:
return self.inorderSuccessor(root.right, p)
left = self.inorderSuccessor(root.left, p)
if left == None:
return root
else:
return left
该博客介绍了如何在二叉搜索树中找到给定节点的后继节点。通过中序遍历的思路,如果当前根节点值小于或等于目标节点值,则在右子树中寻找;否则,在左子树中递归寻找。如果左子树的递归结果为null,则当前根节点是后继,否则返回左子树的递归结果。

917

被折叠的 条评论
为什么被折叠?



