Python implements Binary Tree Structure and implements binary tree traversal.

Source: Internet
Author: User

Python implements Binary Tree Structure and implements binary tree traversal.

Build a binary tree

Define a binary tree in the form of classes for 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.right_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.keyr = 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 performs binary tree traversal

Requirements:
Python code implements Binary Tree:
1. Print the traversal result in the forward order.
2. Print the traversal result in the middle order.
3. Print the traversal result in the descending order.
4. Print the traversal result by level of the tree.
5. If there are no subnodes in the next layer of the node, replace them with 'N '.

Method:
Use defaultdict or namedtuple to represent a binary tree
Use the StringIO method to write the results over time and print the results.
When printing the node value, if it is null, StringIO () writes 'n'
Recursive access to subnodes
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,           Node(8, None, None),           Node(9, None, None)),         None))#read and write str in memoryoutput = StringIO()#read the node and write the node's value#if node is None, substitute with 'N 'def visitor(node):  if node is 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(node.left, order),        'R': lambda: traversal(node.right, order),    }    for x in order:      op[x]()#traversal the tree level by leveldef traversal_level_by_level(node):  if node is not 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.append('N')          if n.right is not None:            next_level.append(n.right)          else:            next_level.append('N ')      output.write('\n')      current_level = next_levelif __name__ == '__main__':  for order in ['NLR', 'LNR', 'LRN']:    if order == 'NLR':      output.write('this is preorder traversal:')      traversal(tree, order)      output.write('\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('traversal level by level as below:'+'\n')  traversal_level_by_level(tree)  print(output.getvalue())

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.