How Python programming implements a two-fork tree and seven ways to traverse

Source: Internet
Author: User
This article mainly introduces the Python programming implementation of two-fork tree and seven kinds of traversal methods, combined with the example of a detailed analysis of the Python two fork tree definition and common traversal operation skills, the need for friends can refer to the next

This paper describes the implementation of Python two fork tree and traversal method. Share to everyone for your reference, as follows:

Introduced:

Tree is a very important data structure, the main purpose is to improve the search efficiency, for the case of repeated lookups, such as binary sorting tree, fp-tree. It can also be used to improve coding efficiency, such as Havermann trees.

Code:

Using Python to implement tree construction and several traversal algorithms, although not difficult, but still the code for a summary of the collation. Implementation features:

The structure of the ① tree
② recursive implementation of first order traversal, middle sequence traversal, post-order traversal
③ Stack implements first order traversal, middle sequence traversal, post-order traversal
④ Queue Implementation Hierarchy traversal

#coding =utf-8class Node (object): "" "Node Class" "Def init (self, elem=-1, Lchild=none, rchild=none): Self.elem = Elem sel F.lchild = lchild Self.rchild = Rchildclass Tree (object): "" "Tree Class" "Def init (self): Self.root = Node () self.myqu Eue = [] def add (self, Elem): "" "Add Node for tree" "" "Nodes = node (elem) If Self.root.elem = =-1: # If the tree is empty, assign a value to the root node self      . root = Node Self.myQueue.append (self.root) Else:treenode = self.myqueue[0] # The subtree of this node is not yet aligned. if Treenode.lchild = = None:treeNode.lchild = Node Self.myQueue.append (treenode.lchild) else:tr  Eenode.rchild = node Self.myQueue.append (treenode.rchild) self.myQueue.pop (0) # If the node has a right subtree, discard the node. def Front_digui (self, Root): "" "uses recursion to implement the tree's first order traversal" "If root = = None:return Print Root.elem, Self.front_digui      (root.lchild) Self.front_digui (root.rchild) def middle_digui (self, Root): "" "uses recursion to implement the tree's middle order traversal" "If root = = None:  Return Self.middle_digui (Root.lchild)  Print Root.elem, Self.middle_digui (root.rchild) def later_digui (self, Root): "" "the sequential traversal of the tree using recursion" "If root = = Non E:return Self.later_digui (root.lchild) Self.later_digui (root.rchild) print Root.elem, Def front_stack (self      , root): "" "uses the stack to implement the tree's first order traversal" "If root = = None:return Mystack = [] node = root while node or mystack:      While node: #从根节点开始, keep looking for its left subtree print Node.elem, mystack.append (node) node = Node.lchild node = Mystack.pop () #while结束表示当前节点node为空, that is, the previous node has no left subtree, node = node.rchild #开始查看它的右子树 def middle_stac K (self, Root): "" "uses the stack to implement the tree's middle order traversal" "If root = = None:return Mystack = [] node = root while node or Mysta Ck:while node: #从根节点开始, always find its left subtree mystack.append (node) node = node.lchild node = mystack. Pop () #while结束表示当前节点node为空, that is, the previous node has no left subtree, print node.elem, node = node.rchild #开始查看它的右子树 def later_s Tack (self, Root): "" "Using the stack to implement the tree's post-traversal "" "If root = = None:return MyStack1 = [] MyStack2 = [] node = root mystack1.append (node) While MyStack1: #这个while循环的功能是找出后序遍历的逆序, there is myStack2 inside node = Mystack1.pop () if Node.lchild:my Stack1.append (Node.lchild) if Node.rchild:myStack1.append (node.rchild) mystack2.append (node) while my Stack2: #将myStack2中的元素出栈, which is the post-order traversal sequence, print Mystack2.pop (). Elem, Def level_queue (self, Root): "" "uses the queue to implement the tree's  Hierarchy traversal "" "If root = = None:return Myqueue = [] node = root myqueue.append (node) while Myqueue:node = Myqueue.pop (0) Print Node.elem, if node.lchild! = None:myQueue.append (node.lchild) if Node.rchil D! = None:myQueue.append (node.rchild) If name = = ' main ': "" "Main Function" "" Elems = range #生成十个数据作为树节点 tree = Tr EE () #新建一个树对象 for Elem in Elems:tree.add (elem) #逐个添加树的节点 print ' queue implementation hierarchy traversal: ' Tree.level_queue (tree.root) PR int ' \ n ' recursive implementation of First order traversal: ' TreE.front_digui (tree.root) print ' \ n recursive implementation of a sequential traversal: ' Tree.middle_digui (tree.root) print ' \ n recursively implements post-order traversal: ' Tree.later_digui ( tree.root) print ' \ n ' stack implementation sequencing traversal: ' Tree.front_stack (tree.root) print ' \ n stack implementation in sequence traversal: ' Tree.middle_stack (tree.root) print ' \ nthe stack implementation post-traversal: ' Tree.later_stack (Tree.root)

Summarize:

There are two main types of tree traversal, one is depth-first traversal, such as pre-order, sequence, post-order, and the other is breadth-first traversal, like hierarchical traversal. The difference between the two is not very obvious in the tree structure, but the efficiency and effect of the depth-first search and breadth-first search are very different from the tree extending to the graph to the graph.

Depth first generally uses recursion, and breadth first generally uses queues. Most of the algorithms that can be implemented recursively can also be implemented with stacks.

My impression is that there is a recursive tree method, but I can't think of how to construct it. Later thought carefully, the recursive thought is a bit similar to the depth first algorithm, but the tree construction should be the breadth first. If recursive, there must be a termination condition, such as the provision of tree depth. Otherwise the tree will be constructed to favor the left tree or the right list tree. Therefore, the structure of the general tree should be used in the queue better.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.