@Scrazy
2017-02-27T14:47:18.000000Z
字数 871
阅读 897
python
今天看到群友发了张照片,一道笔试题。。
Date Structure
For Inorder and Preorder traversals
inorder = + d c a - b / * e
preorder = a d + c - * b / e
please construct this tree
大意
中序和前序遍历如题,请构造此树!
刚好最近在啃算法,练练手!用手画了画,树应该是这样的。
。
下面就用代码测试下看看。
# code=utf-7
class Node:
def __init__(self, key):
self.val = key
self.left = None
self.right = None
def inorderprint(root):
if root:
inorderprint(root.left)
print(root.val)
inorderprint(root.right)
def preprint(root):
if root:
print(root.val)
preprint(root.left)
preprint(root.right)
def postprint(root):
if root:
postprint(root.left)
postprint(root.right)
print(root.val)
root = Node('a')
root.left = Node('d')
root.left.left = Node('+')
root.left.right = Node('c')
root.right = Node('-')
root.right.right = Node('*')
root.right.right.left = Node('b')
root.right.right.right = Node('e')
root.right.right.left.right = Node('/')
>>> inorderprint(root)
+
d
c
a
-
b
/
*
e
>>> preprint(root)
a
d
+
c
-
*
b
/
e
>>> postprint(root)
+
c
d
/
b
e
*
-
a
正确!顺便把后续的也打印了!