class
TreeNode:
def
__init__(
self
, x):
self
.val
=
x
self
.left
=
None
self
.right
=
None
def
create(postfix,infix,length):
if
length
=
=
0
:
return
None
temp
=
TreeNode(postfix[length
-
1
])
root_index
=
0
while
root_index<length:
if
infix[root_index]
=
=
postfix[length
-
1
]:
break
root_index
+
=
1
print
(temp.val,end
=
' '
)
if
length>
1
:
temp.left
=
create(postfix,infix,root_index)
temp.right
=
create(postfix[root_index:],infix[root_index
+
1
:],length
-
root_index
-
1
)
else
:
temp.left
=
None
temp.right
=
None
return
temp
postfix
=
input
(
'输入后序'
).split(
' '
)
infix
=
input
(
'输入中序'
).split(
' '
)
length
=
len
(infix)
print
(
'-------------前序输出----------------'
)
root
=
create(postfix,infix,length)
print
(
'\n-------------层序输出----------------'
)
queue
=
[root]
while
len
(queue)!
=
0
:
x
=
queue.pop(
0
)
print
(x.val,end
=
' '
)
if
x.left
is
not
None
:
queue.append(x.left)
if
x.right
is
not
None
:
queue.append(x.right)