给定树的根结点指针TreeNode* root和结点的值int p,编写一个函数,寻找该二叉树中指定结点的下一个结点(即中序遍历的后继),并返回p结点的后继结点的值。保证结点的值是小于等于100000的正数且没有重复值,若不存在后继返回-1。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Successor:
def findSucc(self, root, p):
if not root:
return -1
stack = []
ph = root
isFind = False
result = -1
while ph or stack:
while ph:
stack.append(ph)
ph = ph.left
if stack:
top = stack.pop()
if isFind:
result = top.val
break
if top.val == p:
isFind = True
ph = top.right
return result