Python Checking paths to leaf in binary tree pytho

2019-03-03 08:53发布

Lets say i have this tree:

                                     cough
                      Yes /                            \ No
                   sneezing                        sneezing
               Yes /       \ No                Yes /       \ No
             fever         fever               fever         fever
       Yes /    \ No    Yes/     \No       Yes /    \ No    Yes/     \No
       dead   cold   influenza   cold      dead   influenza cold   healthy

And i want the paths to the illness "influenza" What the output should be is like this:

[[True,False,True],[False,True,False]]

If you go to right of the root it return True ( Yes ) , if you go to Left its False( No)

This is the code I have been trying to do for this function but im doing something wrong it returns not as i want..

def paths_to_illness(self, illness):

    head=self.__root
    new_list=[]
    new_list=diagnoser.get_path(head,illness)
    return new_list

def get_path(self,head,illness):

    if head is None:
        return []
    if (head.positive_child == None and head.negative_child==None):
        return [head.data]

    left_tree=diagnoser.get_path(head.negative_child,illness)
    right_tree=diagnoser.get_path(head.positive_child,illness)
    all_tree=left_tree+right_tree

    list1=[]

    for leaf in  all_tree:

        if illness == leaf:

            list1.append(["True"])
        else:
            list1.append(["False"])

    return list1

any ideas to help me fix my code? thanks

the diagonser is just a class not important, my node class have the right as "positive_child" and left "negative_child"

if anything else is unclear please let me know

thanks!.

Upon request my code for making the tree:

class Diagnoser:
def __init__(self, root):
    self.__root = root


class Node:
 def __init__(self, data="", pos=None, neg=None):
    self.data = data
    self.positive_child = pos
    self.negative_child = neg


leaf1 = Node("dead", None, None)
leaf2 = Node("cold", None, None)
fever1 = Node("fever", leaf1, leaf2)

leaf3 = Node("influenza", None, None)
leaf4 = Node("cold", None, None)
fever2 = Node("fever", leaf3, leaf4)

sneezing1 = Node("sneezing", fever1, fever2)

leaf5 = Node("dead", None, None)
leaf6 = Node("influenza", None, None)
fever3 = Node("fever", leaf5, leaf6)

leaf7 = Node("cold", None, None)
leaf8 = Node("healthy", None, None)
fever4 = Node("fever", leaf7, leaf8)

sneezing2 = Node("sneezing", fever3, fever4)

root = Node("cough", sneezing1, sneezing2)
diagnoser = Diagnoser(root)

1条回答
Root(大扎)
2楼-- · 2019-03-03 09:02

Here's what I came up with

class Tree:
  def __init__(self, data, left=None, right=None):
    self.data = data
    self.left = left
    self.right = right

  @property
  def is_leaf(self):
    return not (self.left or self.right)

  def __repr__(self):
    return 'Tree({}, {}, {})'.format(self.data, self.left, self.right)

  def find(self, target, path_to=()):
    if self.is_leaf:
      if self.data == target:
        yield path_to
    else:
      if self.left:
        yield from self.left.find(target, (*path_to, True))
      if self.right:
        yield from self.right.find(target, (*path_to, False))

t = Tree('Cough', Tree('Sneezing', Tree('Fever', Tree('Dead'), Tree('Cold')), Tree('Fever', Tree('Influenza'), Tree('Cold'))), Tree('Sneezing', Tree('Fever', Tree('Dead'), Tree('Influenza')), Tree('Fever', Tree('Cold'), Tree('Healthy'))))

print(list(t.find('Influenza')))

By having our find method be a generator, we can easily bubble positive results up the call stack using yield from. If you're using a version of Python that doesn't support argument unpacking (*path_to, True), then path_to + (True,) is equivalent

Edit: Here's a version the doesn't use yield

def find(self, target, path_to=()):
  if self.is_leaf:
    if self.data == target:
      return [path_to]
    else:
      return []
  else:
    if self.left:
      l = self.left.find(target, (*path_to, True))
    if self.right:
      r = self.right.find(target, (*path_to, False))
    return l + r
查看更多
登录 后发表回答