Python data structure-binary tree traversal instance

Source: Internet
Author: User
This article mainly introduces the recursive traversal instance of a binary tree in python data structure. For more information, see Traversal scheme
The recursive definition of a binary tree shows that a non-empty binary tree consists of the root node and the left and right subtrees. Therefore, you can execute three operations in a certain order on any given node:
1). access node itself (N)
2). traverse the left subtree of the node (L)
3). traverse the right subtree of the node (R)

Order:
NLR, LNR, LRN

Name of traversal

Name an access node based on its operation location:
NLR: PreorderTraversal (also known as PreorderTraversal)-the access node operation occurs before traversing its left and right subtree.
LNR: InorderTraversal-the operation of the access node occurs in the left and right subtrees ).
LRN: Post-sequential traversal (PostorderTraversal)-The operation to access a node occurs after traversing its left and right subtree.

Note: Because the Accessed Node must be the root of a subtree, N (Node), L (Left subtlee), and R (Right subtree) it can also be interpreted as the root, the left subtree of the root, and the right subtree of the root. NLR, LNR, and LRN are also called root traversal, root traversal, and Root traversal respectively.

Traversal algorithm

1). recursive algorithm definition for sequential traversal:
If the binary tree is not empty, perform the following operations in sequence:
A. access the root node
B. traverse the left subtree
C. traverse the right subtree

2). recursive algorithm definition for sequential traversal:
If the binary tree is not empty, perform the following operations in sequence:
A. traverse the left subtree
B. access the root node
C. traverse the right subtree

3). recursive algorithm definition for post-order traversal:
If the binary tree is not empty, perform the following operations in sequence:
A. traverse the left subtree
B. traverse the right subtree
C. access the root node

1. recursive traversal of binary trees:

The code is as follows:


#-*-Coding: utf-8 -*-

Class TreeNode (object ):

Def _ init _ (self, left = 0, right = 0, data = 0 ):
Self. left = left
Self. right = right
Self. data = data


Class BTree (object ):

Def _ init _ (self, root = 0 ):
Self. root = root

Def is_empty (self ):
If self. root is 0:
Return True
Else:
Return False

Def preorder (self, treenode ):
'Pre-order (NLR) traversal'
If treenode is 0:
Return
Print treenode. data
Self. preorder (treenode. left)
Self. preorder (treenode. right)

Def inorder (self, treenode ):
'In-order, LNR'
If treenode is 0:
Return
Self. inorder (treenode. left)
Print treenode. data
Self. inorder (treenode. right)

Def postorder (self, treenode ):
'Post-order (LRN) traversal'
If treenode is 0:
Return
Self. postorder (treenode. left)
Self. postorder (treenode. right)
Print treenode. data


Node1 = TreeNode (data = 1)
Node2 = TreeNode (node1, 0, 2)
Node3 = TreeNode (data = 3)
Node4 = TreeNode (data = 4)
Node5 = TreeNode (node3, node4, 5)
Node6 = TreeNode (node2, node5, 6)
Node7 = TreeNode (node6, 0, 7)
Node8 = TreeNode (data = 8)
Root = TreeNode (node7, node8, 'root ')

Bt = BTree (root)

Print u '''

# Generated binary tree

#------------------------
# Root
#7 8
#6
#2 5
#1 3 4
#
#-------------------------

'''
Print 'pre-order (NLR) traversal: \ n'
Bt. preorder (bt. root)

Print 'in-order (LNR) traversal: \ n'
Bt. inorder (bt. root)

Print 'post-order (LRN) traversal: \ n'
Bt. postorder (bt. root)


II. non-recursive traversal of binary trees

Next we will implement it in a non-recursive way. We mainly use stack and queue to maintain some data nodes:

The code is as follows:


#-*-Coding: utf-8 -*-


Class TreeNode (object ):

Def _ init _ (self, left = 0, right = 0, data = 0 ):
Self. left = left
Self. right = right
Self. data = data


Class BTree (object ):

Def _ init _ (self, root = 0 ):
Self. root = root

Def is_empty (self ):
If self. root is 0:
Return True
Else:
Return False

Def preorder (self, treenode ):
'Pre-order (NLR) traversal'
Stack = []
While treenode or stack:
If treenode is not 0:
Print treenode. data
Stack. append (treenode)
Treenode = treenode. left
Else:
Treenode = stack. pop ()
Treenode = treenode. right

Def inorder (self, treenode ):
'In-order (LNR) traversal'
Stack = []
While treenode or stack:
If treenode:
Stack. append (treenode)
Treenode = treenode. left
Else:
Treenode = stack. pop ()
Print treenode. data
Treenode = treenode. right

# Def postorder (self, treenode ):
# Stack = []
# Pre = 0
# While treenode or stack:
# If treenode:
# Stack. append (treenode)
# Treenode = treenode. left
# Elif stack [-1]. right! = Pre:
# Treenode = stack [-1]. right
# Pre = 0
# Else:
# Pre = stack. pop ()
# Print pre. data

Def postorder (self, treenode ):
'Post-order (LRN) traversal'
Stack = []
Queue = []
Queue. append (treenode)
While queue:
Treenode = queue. pop ()
If treenode. left:
Queue. append (treenode. left)
If treenode. right:
Queue. append (treenode. right)
Stack. append (treenode)
While stack:
Print stack. pop (). data

Def levelorder (self, treenode ):
From collections import deque
If not treenode:
Return
Q = deque ([treenode])
While q:
Treenode = q. popleft ()
Print treenode. data
If treenode. left:
Q. append (treenode. left)
If treenode. right:
Q. append (treenode. right)


Node1 = TreeNode (data = 1)
Node2 = TreeNode (node1, 0, 2)
Node3 = TreeNode (data = 3)
Node4 = TreeNode (data = 4)
Node5 = TreeNode (node3, node4, 5)
Node6 = TreeNode (node2, node5, 6)
Node7 = TreeNode (node6, 0, 7)
Node8 = TreeNode (data = 8)
Root = TreeNode (node7, node8, 'root ')


Bt = BTree (root)

Print u '''

# Generated binary tree

#------------------------
# Root
#7 8
#6
#2 5
#1 3 4
#
#-------------------------

'''
Print 'pre-order (NLR) traversal: \ n'
Bt. preorder (bt. root)

Print 'in-order (LNR) traversal: \ n'
Bt. inorder (bt. root)

Print 'post-order (LRN) traversal: \ n'
Bt. postorder (bt. root)

Print 'Level-order, LRN) traversal: \ n'
Bt. levelorder (bt. root)

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.