how to draw binary trees whose preorder listing is abcdefgh and whose postorder listing is dcbgfhea.also,list the nodes of binary trees in inorder and level order ?
A:
Here's a simple Python program that generates all possible inorder listings based on preorder and postorder listings.
from itertools import product
def inorders(pre, pos):
if not pre: return [""]
ret = []
if pre[0] == pos[-1]:
for left_size in range(len(pre)):
left = inorders(pre[1:left_size+1], pos[:left_size])
right = inorders(pre[left_size+1:], pos[left_size:-1])
for l, r in product(left, right):
ret.append(l + pre[0] + r)
return ret
And here's the output for your case:
>>> inorders("abcdefgh", "dcbgfhea")
['bcdafgeh', 'bcdagfeh', 'bdcafgeh', 'bdcagfeh', 'cdbafgeh', 'cdbagfeh', 'dcbafgeh', 'dcbagfeh']
Sheldon L. Cooper
2010-09-26 23:34:51
since you don't ever use `n`, you can just replace the first two lines of `inorder` with `if not pre: return ['']`
aaronasterling
2010-09-26 23:44:17
@AaronMcSmooth - I used `n` twice, but I made the change anyways. Thanks.
Sheldon L. Cooper
2010-09-26 23:48:24