二叉树前、中、后序遍历
原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/14950846.html
class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None class BinaryTree: def __init__(self, root): self.root = TreeNode(root) def pre_order_traversal(self, root): """root -> left -> right""" if root is None: return print(root.data) self.pre_order_traversal(root.left) self.pre_order_traversal(root.right) return root def in_order_traversal(self, root): """left -> root -> right""" if root is None: return self.in_order_traversal(root.left) print(root.data) self.in_order_traversal(root.right) return root def post_order_traversal(self, root): """left -> right -> root""" if root is None: return self.post_order_traversal(root.left) self.post_order_traversal(root.right) print(root.data) return root # 1 # 2 3 # 4 5 6 7 tree = BinaryTree(1) tree.root.left = TreeNode(2) tree.root.right = TreeNode(3) tree.root.left.left = TreeNode(4) tree.root.left.right = TreeNode(5) tree.root.right.left = TreeNode(6) tree.root.right.right = TreeNode(7) print("pre_order_traversal: ") tree.pre_order_traversal(tree.root) print("in_order_traversal: ") tree.in_order_traversal(tree.root) print("post_order_traversal: ") tree.post_order_traversal(tree.root)
强者自救 圣者渡人