Multiple implementations of Binary Tree creation and traversal (python version), binary tree python

Source: Internet
Author: User

Multiple implementations of Binary Tree creation and traversal (python version), binary tree python

Binary Tree is an important data structure and plays an important role in interviews and daily development.

The first is the process of building a tree. Compared with the implementation of C or C ++, it involves complicated pointer operations. However, in object-oriented languages, pointers do not need to be considered, memory. First, we need to define a tree node. We adopt a node based on the linked list. First, we need to define a data field, followed by left and right children. Definition:

# Tree Node definition class Node: def _ init _ (self, data =-1, lchild = None, rchild = None): self. lchild = lchild # indicates the left subtree self. rchild = rchild # indicates the right subtree self. data = data # indicates the data domain

 

There are two types of tree creation implementation: traversal and hierarchy. These two types are implemented based on stacks and queues. First, let's take a look at the most basic recursive tree creation.
The process of building a recursive tree is nothing more than going all the way to the end, but the left and right child nodes of the node need to be associated with the remaining nodes. Therefore, we can achieve this:

def traversal_create(self, root):data = input()if data is "#":return Noneelse:root.data = dataroot.lchild = self.traversal_create(root.lchild)root.rchild = self.traversal_create(root.rchild)return root

First, the input parameter is a default node, and its data field is-1. Then, we accept the input data and assign it to the node data field, which is then recursive, associate left and right child nodes. In general, it is not difficult to understand.

Next let's take a look at the implementation of hierarchy building. The so-called hierarchy building is actually queue-based operations. With the features of first-in-first-out queues, each time we access a node, we store it in the queue, when you traverse the left and right child nodes of the current node, a node pops up in the queue, and the subsequent operations are the same. Look at the Code:

Def add (self, elem): node = Node (elem) # root node if self. root. data =-1: self. root = nodeself. myQueue. append (self. root) else: treeNode = self. myQueue [0] # record the node if treeNode. lchild is None: treeNode. lchild = nodeself. myQueue. append (treeNode. lchild) else: treeNode. rchild = nodeself. myQueue. append (treeNode. rchild) self. myQueue. popleft () # pop up the parent node that has processed the left and right subtree

Input a data, initialize a node based on the data, and put it into the queue. Then, access is performed.

Needless to say, the three-order traversal of the tree is based on recursion and good understanding. What about the traversal based on queue and stack?
Compared with the queue-based creation, we can write queue-based traversal. We also use queues to store nodes and then output the data of left and right children:

# Hierarchical traversal Use Queue def queue_tarversal (self, root): if root is None: returnq = 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 stack-based? Think of the characteristics of the stack, we traverse along the left subtree, and use the stack to store elements, and then traverse the right child node in the pop-up window:

# Use a stack to traverse def stack_traversal (self, root): if root is None: returnmystack = [] node = rootwhile node or mystack: while node: print (node. data) mystack. append (node) node = node. lchildnode = mystack. pop () node = node. rchild

Data structure is both difficult and basic, so you should study it all.

Complete code:

'''Establishment and implementation of a binary tree (recursion and non-recursion) ''' from collections import deque # class Node: def _ init _ (self, data =-1, lchild = None, rchild = None): self. lchild = lchild # indicates the left subtree self. rchild = rchild # indicates the right subtree self. data = data # indicates the data domain class Create_Tree: def _ init _ (self): self. root = Node () # indicates Node self. myQueue = deque () # using queues does not have much memory overhead # generate tree def add (self, elem) by hierarchy: node = Node (elem) # root node if self. root. data =-1: self. root = node self. myQueue. append (self. root) else: treeNode = self. myQueue [0] # record the node if treeNode. lchild is None: treeNode. lchild = node self. myQueue. append (treeNode. lchild) else: treeNode. rchild = node self. myQueue. append (treeNode. rchild) self. myQueue. popleft () # pop up the parent node that has processed the left and right subtree # recursive build def traversal_create (self, root): data = input () if data is "#": return None else: root. data = data root. lchild = self. traversal_create (root. lchild) root. rchild = self. traversal_create (root. rchild) return root # output def digui (self, root): if root is None: return print (root. data) self. digui (root. lchild) self. digui (root. rchild) # use a stack to traverse def stack_traversal (self, root): if root is None: return mystack = [] node = root while node or mystack: while node: print (node. data) mystack. append (node) node = node. lchild node = mystack. pop () node = node. rchild # Use the queue def queue_tarversal (self, root): if root is None: return q = deque () q for hierarchical traversal. 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) if _ name _ = "_ main _": elems = range (10) tree = Create_Tree () for I in elems: # non-recursive build, it is mainly based on the characteristics of queue FIFO and the concept of breadth traversal tree. add (I) # recursive build # tree. traversal_create (tree. root) # recursively traverse the tree. digui (tree. root) # stack traversal # tree. stack_traversal (tree. root)
View Code

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.