class Node:
def __init__(self,data):
self.data=data
self.lchild=None
self.rchild=None
class Tree:
def __init__(self):
self.queue=[]#利用隊列存儲樹的節點
self.flag=0#存儲樹根後flag置爲1
self.root=None
#建樹
def createTree(self, list):
while True:
#list中沒有數據,表示建樹完成
if len(list) == 0:
return
#flag爲0,表示樹根不存在
if self.flag == 0:
self.root = Node(list[0])
#講樹根存入隊列
self.queue.append(self.root)
#樹根已創建,flag置爲1
self.flag = 1
#剔除list中第一個已經使用數
list.pop(0)
else:
'''
treeNode:隊列中的第一個節點(該節點左右孩子不完全存在)
添加treeNode的左右孩子,當添加treeNode的右孩子之後,
將隊列中的第一個節點出隊。
'''
treeNode=self.queue[0]
if treeNode.lchild==None:
treeNode.lchild=Node(list[0])
self.queue.append(treeNode.lchild)
list.pop(0)
else:
treeNode.rchild = Node(list[0])
self.queue.append(treeNode.rchild)
list.pop(0)
self.queue.pop(0)
# 隊棧實現中序遍歷
def middle_queueAndStack(self, root):
if root is None:
return
# 定義一個棧,存儲節點
stack = []
node = root
ans = []
while stack or node:
# 一直查找樹的左節點,一直進棧
while node:
stack.append(node)
node = node.lchild
node = stack.pop() # 該節點不存在左節點,該節點出棧,查找右節點
ans.append(node.data)
node = node.rchild
return ans
if __name__ == '__main__':
num = list(map(int, input().split(',')))
point = eval(input())
tree = Tree()
tree.createTree(num)
ans = tree.middle_queueAndStack(tree.root)
output = -1
for idx, i in enumerate(ans):
if i == point and idx != len(ans) - 1:
output = ans[idx + 1]
break
print(output)
先通過給定層次遍歷序列得到二叉樹,然後中序遍歷二叉樹,然後在中序遍歷的結果中找當前節點的下一個即可。但是我只有91,應該有種什麼情況沒有考慮到,希望大佬們指點。
在牛客網上有大佬說當輸入是非數字的情況下輸出 -1, 我就很開(ri)心(gou),好的,這種情況以後咱一定考慮到。