Python implementation of the two-fork tree structure and the method of binary tree traversal

Source: Internet
Author: User
Establishment of Binary tree

Define a binary tree in the form of a class, with better readability

Class Binarytree:def __init__ (self, root): Self.key = root Self.left_child = None Self.right_child = None def Insert_left (self, new_node): if Self.left_child = = None:self.left_child = BinaryTree (new_node) else:t =  BinaryTree (new_node) t.left_child = Self.left_child Self.left_child = t def insert_right (self, new_node): if Self.right_child = = None:self.right_child = BinaryTree (new_node) else:t = BinaryTree (new_node) T.righ T_child = Self.right_child Self.right_child = t def get_right_child (self): return self.right_child def Get_left_ Child (self): return self.left_child def set_root_val (self, obj): Self.key = obj def get_root_val (self): return Self.key r = BinaryTree (' a ') print (R.get_root_val ()) print (R.get_left_child ()) r.insert_left (' B ') print (R.get_left_ Child ()) print (R.get_left_child (). Get_root_val ()) r.insert_right (' C ') print (R.get_right_child ()) Print (r.get_right _child (). Get_root_val ()) R.get_right_child (). Set_root_val (' Hello ') print (R.get_right_child (). Get_root_val ()) 

Python for binary tree traversal

Demand:
Python code implements a two-fork tree:
1. Pre-sequence traversal, print out the traversal results
2. Middle sequence traversal, print out the traverse result
3. Post-step traversal, print out the traversal results
4. Traverse through the level of the tree to print out the traversal results
5. If there is no child node in the next layer of the node, replace it with ' N '

Method:
Use Defaultdict or namedtuple to denote a binary tree
Use the Stringio method to write the results when traversing, and finally print out the results
When printing a node value, if NULL, Stringio () writes ' N '
Using recursive access to child nodes
Code

#!/usr/bin/env python3#-*-coding:utf-8-*-# Test tree as below: ' 1/\/\ \ \/\ 2 3/\ \ \/\/\ 4 5 6 N/\/ \/\ 7 N n n 8 9/\/\ \ \ n n n n. N n ' from collections import namedtuplefrom IO import Stringio #define the node Structurenode = Namedtuple (' node ', [' data ', ' left ', ' right ']) #initialize The Treetree = node (1, node (2, node) ( 4, Node (7, none, none), none), node (5, none, none), node (3, node (6, No) De (8, none, none), Node (9, none, none)), none)) #read and write str in memoryoutput = Stringio () #read t He node and write the node ' s value#if node is None, substitute with ' N ' Def Visitor (node): If node was not none:output . Write ('%i '% node.data) else:output.write (' N ') #traversal the tree with different orderdef traversal (node, order) : If node is none:visitor (node) else:op = {' N ': lambda:visitor (node), ' L ': Lambda:traversal (nod E.left, order), 'R ': Lambda:traversal (node.right, Order),} for X in Order:op[x] () #traversal The tree level by Leveldef Trav Ersal_level_by_level (node): if node isn't none:current_level = [node] while current_level:next_level = List () for N in Current_level:if type (n) is Str:output.write (' n ') else:output.write (' %i '% n.data) if N.left is not None:next_level.append (n.left) ELSE:NEXT_LEVEL.A Ppend (' N ') if N.right is not None:next_level.append (n.right) Else:next_level.app End (' n ') output.write (' \ nthe ') Current_level = next_level if __name__ = = ' __main__ ': for order in [' NLR ', ' LNR ' , ' LRN ']: if order = = ' NLR ': output.write (' This is preorder traversal: ') traversal (tree, order) OUTPUT.W Rite (' \ n ') elif order = = ' LNR ': output.write (' This is inorder traversal: ') traversal (tree, order) output   . write (' \ n ') Else:   Output.write (' This is postorder traversal: ') traversal (tree, order) output.write (' \ n ') output.write (' Traver Sal level by level as below: ' + ' \ n ') traversal_level_by_level (tree) print (Output.getvalue ())

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.