[关闭]
@WillireamAngel 2018-05-28T07:56:37.000000Z 字数 1155 阅读 1086

树的遍历

数据结构


  1. #!/bin/python
  2. #-*- coding = utf-8 -*-
  3. class tree:
  4. def __init__(self,data):
  5. self.left = None
  6. self.right = None
  7. self.data = data
  8. def insert(self,data):
  9. if self.data:
  10. if data < self.data:
  11. if self.left is None:
  12. self.left = tree(data)
  13. else:
  14. self.left.insert(data)
  15. if data > self.data:
  16. if self.right is None:
  17. self.right = tree(data)
  18. else:
  19. self.right.insert(data)
  20. else:
  21. self.data = data
  22. def printTree(self):
  23. if self.left:
  24. self.left.printTree()
  25. print(self.data)
  26. if self.right:
  27. self.right.printTree()
  1. root = tree(27)
  2. root.insert(14)
  3. root.insert(35)
  4. root.insert(10)
  5. root.insert(19)
  6. root.insert(31)
  7. root.insert(42)
  8. root.printTree()
  9. print(root.inorder(root))

中序遍历

将每个节点理解成一棵树,然后按照从左子树-根-右子树的顺序逐级遍历,从最底层开始。

  1. def inorder(self,root):
  2. result = []
  3. if root:
  4. result = self.inorder(root.left)
  5. result.append(root.data)
  6. result += self.inorder(root.right)
  7. return result

前序遍历

将每个节点理解成一棵树,然后按照从根-左子树-右子树的顺序逐级遍历,从根开始。

  1. def preorder(self,root):
  2. result = []
  3. if root:
  4. result.append(root.data)
  5. result += self.inorder(root.left)
  6. result += self.inorder(root.right)
  7. return result

后序遍历

将每个节点理解成一棵树,然后按照从左子树-右子树-根的顺序逐级遍历,从最底层左子树开始。

  1. def postorder(self,root):
  2. result = []
  3. if root:
  4. result += self.inorder(root.left)
  5. result += self.inorder(root.right)
  6. result.append(root.data)
  7. return result
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注