二叉树后序遍历
思路1:
先根据前序、中序得到二叉树,再将二叉树以后序遍历输出。
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if len(pre)==0:
return None
root=TreeNode(pre[0])
TinIndex=tin.index(pre[0])
root.left=self.reConstructBinaryTree(pre[1:TinIndex+1], tin[0:TinIndex])
root.right=self.reConstructBinaryTree(pre[TinIndex+1:], tin[TinIndex+1:])
return root
def postorderTraversal(self, root):
if not root:
return []
left = self.postorderTraversal(root.left)
right = self.postorderTraversal(root.right)
return left + right + [root.val]
pre, tin = input().split(" ")
# print(pre)
# print(tin)
S=Solution()
root=S.reConstructBinaryTree(pre,tin)
result = S.postorderTraversal(root)
print("".join(result))
相关思路可参考:已知二叉树的前序遍历和中序遍历,如何得到它的后序遍历