简体   繁体   中英

How to parse a tree in python?

I have an expression as follow: ( root (AA ( CC) (DD) ) (BB (CC) (DD) ) )

I want to parse this expression using recursion and I created a tree class but I'm stuck after this man.

This looks this the following tree.

                   root
                     |
                ____________
              AA           BB
              |             |  
       __________         ___________
      CC      DD          CC      DD

The output should look like this:

Root -> AA BB
AA -> CC DD
BB -> CC DD

My tree class look like the following:

 class tree_parsing(object):

     def __init__(self, element=None):
         self.element = element
         self.children = []

Basically I want to store the children in a list member variable of the class. Can someone help figure this problem out? Thank You.

You can do something like this:

#!python
# -*- coding: utf-8 -*-

class Node(object):
  def __init__(self, name, left=None, right=None):
    self.name = name
    self.left = left
    self.right = right

def dump_tree(node):
  if node.left or node.right:
    left = 'None' if node.left is None else node.left.name
    right = 'None' if node.right is None else node.right.name
    print('{0} -> {1} {2}'.format(node.name, left, right))

  if node.left:
    dump_tree(node.left)

  if node.right:
    dump_tree(node.right)


Root = Node(
  'Root', Node('AA', Node('CC'), Node('DD')),
          Node('BB', Node('CC'), Node('DD')),
)

dump_tree(Root)

prints:

$ python example.py
Root -> AA BB
AA -> CC DD
BB -> CC DD
$
class Tree(object):
  def __init__(self, name, left=None, right=None):
    self.name = name
    self.left = left
    self.right = right

def Tree_Parsing(tree):
  if tree.left != None and tree.right != None:
    print tree.name + '->' + tree.left.name + ' ' + tree.right.name
    Tree_Parsing(tree.left)
    Tree_Parsing(tree.right)

Object = Tree( 'Root', Tree('AA', Tree('CC'), Tree('DD')), Tree('BB', Tree('CC'), Tree ('DD')),)
)

Tree_Parsing(Object)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM