[关闭]
@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

大意
中序和前序遍历如题,请构造此树!

刚好最近在啃算法,练练手!用手画了画,树应该是这样的。
答案
下面就用代码测试下看看。

  1. # code=utf-7
  2. class Node:
  3. def __init__(self, key):
  4. self.val = key
  5. self.left = None
  6. self.right = None
  7. def inorderprint(root):
  8. if root:
  9. inorderprint(root.left)
  10. print(root.val)
  11. inorderprint(root.right)
  12. def preprint(root):
  13. if root:
  14. print(root.val)
  15. preprint(root.left)
  16. preprint(root.right)
  17. def postprint(root):
  18. if root:
  19. postprint(root.left)
  20. postprint(root.right)
  21. print(root.val)
  22. root = Node('a')
  23. root.left = Node('d')
  24. root.left.left = Node('+')
  25. root.left.right = Node('c')
  26. root.right = Node('-')
  27. root.right.right = Node('*')
  28. root.right.right.left = Node('b')
  29. root.right.right.right = Node('e')
  30. root.right.right.left.right = Node('/')
  31. >>> inorderprint(root)
  32. +
  33. d
  34. c
  35. a
  36. -
  37. b
  38. /
  39. *
  40. e
  41. >>> preprint(root)
  42. a
  43. d
  44. +
  45. c
  46. -
  47. *
  48. b
  49. /
  50. e
  51. >>> postprint(root)
  52. +
  53. c
  54. d
  55. /
  56. b
  57. e
  58. *
  59. -
  60. a

正确!顺便把后续的也打印了!

参考

Tree Traversals

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注