For any of the nodes, you can perform three operations in a certain order:
- Access node itself (N)
- Zuozi (L) traversing the node.
- To traverse the right subtree of the node (R)
Used to denote the order, that is, the preamble nlr/the lnr/sequence of LRN.
The following we use Namedtuple to express the tree, and the traversal function of the kill with an order parameter, as long as we pass in the specified order to achieve the corresponding traversal.
#coding =utf-8 ' 1///2 3/\/4 5 6//7 8 9 "From collections import namedtuplefrom sys import stdoutnode = namedtuple (' node ', [' data ', ' left ', ' right ']) tree = Node (1, node (2, node (4, Node (7, none, none), none), Node (5, none, none)), node (3, node (6, Node (8, none, none), Node (9, none, none)), none) def visitor (i): Stdout.write ("%i"%i) def Traversal (node, O Rder): #这个是主角, pass kill function if not node:return op = {' N ': Lambda:visitor (node.data), ' L ': Lambda:traversa L (node.left, order), ' R ': lambda:traversal (node.right, Order),} for X in Order:op[x] () for order I n [' NLR ', ' LNR ', ' LRN ']: Traversal (tree, order) print
Elegant Python-simple post-kill function in front of a minimalist two-fork tree