原题
https://leetcode.com/problems/inorder-successor-in-bst/
解法1
中序遍历, 找出p.val后面的节点, 如果没有就返回None.
代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inorderSuccessor(self, root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
"""
l = []
def inOrder(root):
if not root:
return
inOrder(root.left)
l.append(root.val)
inOrder(root.right)
inOrder(root)
i = l.index(p.val)
return TreeNode(l[i+1]) if i< len(l)-1 else None
解法2
递归
代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inorderSuccessor(self, root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
"""
# base case
if not root:
return None
if p.val < root.val:
return self.inorderSuccessor(root.left, p) or root
return self.inorderSuccessor(root.right, p)