AcWing 19. 二叉树的下一个节点(python常规方法中序遍历)
原题链接
中等
作者:
YoloVMe50
,
2023-12-10 15:33:33
,
所有人可见
,
阅读 47
python代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.father = None
class Solution(object):
def inorderSuccessor(self, q):
"""
:type q: TreeNode
:rtype: TreeNode
"""
root=q
self.cur=[]
while root.father:
root=root.father
self.inoder(root)
# print(self.cur)
#如果超出索引值
if self.cur.index(q.val)+3>len(self.cur):
return None
#+2找到中序遍历的下一个节点
res=TreeNode(self.cur[self.cur.index(q.val)+2])
return res
def inoder(self,root):
if root is None:
self.cur.append(None)
return
self.inoder(root.left)
self.cur.append(root.val)
self.inoder(root.right)
这里的数据还是很少,多的话可能会有超时的风险