/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {
st := []*TreeNode{}
var pre, cur *TreeNode = nil, root
for len(st) > 0 || cur != nil {
for cur != nil {
st = append(st, cur)
cur = cur.Left
}
cur = st[len(st)-1]
st = st[:len(st)-1]
if pre == p {
return cur
}
pre = cur
cur = cur.Right
}
return nil
}
# 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') -> 'TreeNode':
st, pre, cur = [], None, root
while st or cur:
while cur:
st.append(cur)
cur = cur.left
cur = st.pop()
if pre == p:
return cur
pre = cur
cur = cur.right
return None
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {
var successor *TreeNode
if p.Right != nil {
successor = p.Right
for successor.Left != nil {
successor = successor.Left
}
return successor
}
node := root
for node != nil {
if node.Val > p.Val {
successor = node
node = node.Left
} else {
node = node.Right
}
}
return successor
}
# 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') -> 'TreeNode':
successor = None
if p.right:
successor = p.right
while successor.left:
successor = successor.left
return successor
node = root
while node:
if node.val > p.val:
successor = node
node = node.left
else:
node = node.right
return successor