Python implements two-fork tree and its seven traversal modes (recursive + non-recursive) __python

Source: Internet
Author: User
Tags serialization tree serialization

1, the binary tree traversal mode.

Pre-sequence traversal: root or Left

In-sequence traversal: Zogen right

Subsequent traversal: Left and right root

Hierarchy traversal: From top to bottom, from left to right

2. Python creates a new binary tree and its seven kinds of traversal (recursive and non-recursive)

Class Node (): #节点类 def __init__ (self,data =-1): Self.data = Data Self.left = None Self.ri Ght = None class tree (): #树类 def __init__ (self): Self.root = Node () def add (self,data): # for Tree plus
        into node nodes = node (data) If Self.root.data = 1: #如果树为空, assigns a value to the root node Self.root = node Else:myqueue = [] TreeNode = Self.root myqueue.append (treeNode) while my
                    Queue: #对已有的节点进行层次遍历 treeNode = myqueue.pop (0) if not treenode.left: Treenode.left = node return elif not Treenode.right:t
                    reenode.right = node return else:myQueue.append (Treenode.left) Myqueue.append (treenode.right) def pre_order_recursion (self,root): #递归实现前序遍历 if not roo
  T:return      Print Root.data, self.pre_order_recursion (root.left) self.pre_order_recursion (root.right) def p Re_order_stack (self,root): #堆栈实现前序遍历 (non-recursive) if not root:return mystack = [] nod
                E = root while mystack or node:while node: #从根节点开始, always looking for his left subtree print node.data, Mystack.append (node) node = node.left node = mystack.pop () #while结束表示当前节点nod
        E is empty, that is, the previous node has no left subtree. node = node.right #开始查看它的右子树 def in_order_recursion (self,root): #递归实现中序遍历 If not Root:return self.in_order_recursion (root.left) print Root.data, self.in_o Rder_recursion (root.right) def in_order_stack (self,root): #堆栈实现中序遍历 (non-recursive) if not Root:retu
                RN mystack = [] node = root while Mystack or node: #从根节点开始, always looking for its left subtree while node: mystack.aPpend (node) node = node.left node = mystack.pop () print Node.data, nod E = Node.right def post_order_recursion (self,root): #递归实现后序遍历 if not root:return se  Lf.post_order_recursion (Root.left) self.post_order_recursion (root.right) print Root.data, Def
        Post_order_stack (self, root): # Stack implementation sequence traversal (not recursive) # first traverse the root node, then traverse the right subtree, the last is the left subtree, so you can be converted to and first-order traversal of a type, and finally only the results of the traversal of the output is OK. If not root:return myStack1 = [] MyStack2 = [] node = root while MyStack1
                or Node:while node:myStack2.append (node) mystack1.append (node) node = node.right node = mystack1.pop () node = Node.left while MYSTACK2:PR int Mystack2.pop (). Data, Def level_order_queue (self,root): #队列实现层次遍历 (non-recursive) if not Root:ret
Urn Myqueue = []        node = root myqueue.append (node) while Myqueue:node = Myqueue.pop (0) Prin
                T Node.data, if Node.left:myQueue.append (node.left) if node.right:  Myqueue.append (node.right) if __name__ = = ' __main__ ': #主函数 datas = [2,3,4,5,6,7,8,9] tree = Tree () #新建一个树对象 to data in Datas:tree.add (data) #逐个加入树的节点 print ' recursive implementation of the pre-sequence traversal: ' Tree.pre _order_recursion (tree.root) print ' \ n stack implementation forward traversal ' Tree.pre_order_stack (tree.root) print ' \ n \ nthe recursive implementation of the sequence traversal: "Tre
    E.in_order_recursion (tree.root) print "\ n sequence traversal in the stack implementation:" Tree.in_order_stack (tree.root) print ' \ n-recursive implementation of sequential traversal: ' Tree.post_order_recursion (tree.root) print ' \ n stack implementation sequence traversal: ' Tree.post_order_stack (tree.root) print ' \ n Queue Implementation level
 Traversing: ' Tree.level_order_queue (Tree.root)
3. Serialization and deserialization of binary tree

1, Binary tree-----> string (Serialization)

2, String-----> Two fork Tree (deserialization)

How to serialize:

Serialization based on first-order traversal

Traversal serialization based on middle order

Based on sequential traversal serialization

Serialization by layer

Here is an example of a first-order traversal:

Assuming that the serialization result is STR, the initial str is an empty string and the first sequence of the binary tree is traversed if an empty node is encountered, and "#!" is added to the Str end if it encounters a node that is not empty, assuming a node value of 3, plus "3!" at the end of Str

(plus here.) The reason is to prevent ambiguity, such as 12 and 1, 2, after serialization is 12.

Deserialization:

1. Converting strings to arrays

1, choose what kind of traversal method to serialize, choose to use what kind of way to deserialize

2, the result of a tree serialization is unique, the only result generated by the two fork tree is also unique

Two-fork tree serialization by layer traversal

1, with the queue for the binary tree traversal, that is, width first traversal.

2, in addition to the order of access nodes is by layer traversal, the result of the string processing, as described before the same approach.






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.