Inorder Successor in BST(tree traverse)
Last updated
Last updated
"""
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
stack = []
cur = root
prev = None
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
if prev and prev.val == p.val:
return cur
prev = cur
cur = cur.right
return 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:
"""
@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 not root or not p:
return None
if root.val<=p.val:
return self.inorderSuccessor(root.right,p)
else:
left = self.inorderSuccessor(root.left,p)
return left if left else root