Binary tree creation and multiple implementations of traversal (Python version)

Source: Internet
Author: User

Binary tree is a very important data structure, and it is a very important role in the interview and daily Development.

The first is the process of building a tree, compared to the implementation of C or C + +, it involves a more complex pointer operation, but in object-oriented language, there is no need to consider pointers, memory and so on. First we need to define a tree node, we use a linked list design node, first define a data field, followed by the left child and the right child. Defined as follows:

# definition of a tree node class Node:     def __init__ (Self, data=-1, Lchild=none, rchild=None):         = Lchild  #  means left subtree        self.rchild = rchild  #  indicates right subtree        Self.data = Data  #  indicates the field

There are two ways to build a tree, which is based on the stack and the queue, and the first step is to look at the most basic recursive achievements.
The process of recursive achievement is nothing but the way to the end, but it is necessary to link the left and right child nodes of the node to the rest of the nodes. So, we can do this:

def= input ()ifis"#":return  Noneelse== = Self.traversal_create (root.rchild)  return root

First we pass in the parameter is a default node, its data field is 1, and then we accept the input data, assigned to the Node data field, and then recursion, the left and right child node Association. Generally speaking, it should not be difficult to understand.

The following look at the implementation of hierarchical achievements, the so-called hierarchy is based on the operation of the queue, the use of advanced first out of the characteristics of the queue, each time we visit a node, put it into the queue, to traverse the current node to play the left and right children node, the queue will pop up a node, after the operation is the same. Look at the code:

defAdd (Self, Elem): node=Node (elem)#root nodeifSelf.root.data = =-1: Self.root=nodeself.myQueue.append (self.root)Else: TreeNode= Self.myqueue[0]#Record NodeifTreenode.lchild isNone:treeNode.lchild=nodeself.myQueue.append (treenode.lchild)Else: Treenode.rchild=nodeself.myQueue.append (Treenode.rchild) self.myQueue.popleft ()#Popup has processed the parent node of the left and right subtree

We enter a data and then initialize a node based on the data, put it in the queue, and then the operation is accessed.

The three-sequence traversal of a tree is needless to say, based on recursion, well understood, then the queue and stack-based traversal?
In contrast to queue-based builds, we can write queue-based traversal, use queues to store nodes, and then output data about children:

 #   hierarchy traversal using queue  def   Queue_tarversal (self, root):  if  root is   None:  return  q  = Deque () q.append (root)  while   Q: Node  = Q.pop ()  print   (node.data)  if  node.lchild is  not   None:q.append (node.lchild)  else  :q.append (node.rchild)  

What about the

Stack-based? With the characteristics of the stack, we go all the way down the left dial hand tree, using the stack to store the elements, and then walk through the right child node in a popup:

# use the stack to traverse def stack_traversal (self, root): if  is None: return  == rootwhileor  mystack: while node:  print== = Node.rchild

The data structure is the difficulty is also the foundation, no matter how kind all should study well.

Full code:

" "establishment and implementation of two-fork tree (recursive and non-recursive)" " fromCollectionsImportdeque#definition of a tree nodeclassNode:def __init__(Self, data=-1, Lchild=none, rchild=None): Self.lchild= Lchild#represents the left sub-treeSelf.rchild = Rchild#represents the right child treeSelf.data = Data#represents a data fieldclassCreate_tree:def __init__(self): Self.root= Node ()#represents a node.Self.myqueue = Deque ()#there is not too much memory overhead for using queues    #spanning trees by hierarchy    defAdd (Self, Elem): node=Node (elem)#root node        ifSelf.root.data = =-1: Self.root=node Self.myQueue.append (self.root)Else: TreeNode= Self.myqueue[0]#Record Node            ifTreenode.lchild isNone:treeNode.lchild=node Self.myQueue.append (treenode.lchild)Else: Treenode.rchild=node Self.myQueue.append (treenode.rchild) self.myQueue.popleft ()#Popup has processed the parent node of the left and right subtree    #Recursive achievements    deftraversal_create (self, root): Data=input ()ifData is "#":            returnNoneElse: Root.data=Data Root.lchild=self.traversal_create (root.lchild) Root.rchild=self.traversal_create (root.rchild)returnRoot#pre-sequence traversal output    defDigui (self, root):ifRoot isNone:return        Print(Root.data) Self.digui (root.lchild) Self.digui (root.rchild)#use the stack to traverse    defstack_traversal (self, root):ifRoot isNone:returnMystack=[] Node=Root whileNodeorMystack: whilenode:Print(node.data) mystack.append (node) node=node.lchild Node=Mystack.pop () node=Node.rchild#hierarchical traversal using queues    defqueue_tarversal (self, root):ifRoot isNone:returnQ=deque () q.append (root) whileQ:node=Q.pop ()Print(Node.data)ifNode.lchild is  notnone:q.append (node.lchild)Else: Q.append (node.rchild)if __name__=="__main__": Elems= Range (10) Tree=Create_tree () forIinchElems:#non-recursive achievements are mainly based on the characteristics of queue FIFO and the idea of breadth traversal.Tree.add (i)#Recursive achievements    #tree.traversal_create (tree.root)    #Recursive traversalTree.digui (tree.root)#Stack Traversal    #tree.stack_traversal (tree.root)
View Code

Binary tree creation and multiple implementations of traversal (Python version)

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.