find a path to a given node in binary tree – Python

Question:

I’m stuck finding the path of the given node so I can find the right side but not the left side.

class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key

    def path(self, k):
      if not self.val:
         return []
      if self.val == k:
        return [self.val]
      res = self.left.path(k)
      if res:
         return [self.val] + res
      res = self.right.path(k)
      if res:
         return [self.val] + res
      return []

For example, when I search for 5 in X="+ * + 5 7 4 1 6", the output is like ['+', '*', '+', '5'] but when I try to search for any number on the lift subtree, it gives me this error:

[Previous line repeated 1 more time]
AttributeError: 'NoneType' object has no attribute 'path'
Asked By: Adam

||

Answers:

Before accessing a method like path you should ensure that the object really is a Node instance, and not None.

Not the problem, but not self.val will also be a true expression when that val is 0, which seems like a valid key for a node… I suppose this test is there to detect a node with a None value. Usually such code is used when a tree is always created with at least one node instance, even when it is empty. This is not good practice. An empty tree should not have nodes at all, not even one with a None value.

So correct to:

class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key

    def path(self, k):
        if self.val == k:
            return [self.val]
        if self.left:
            res = self.left.path(k)
            if res:
                return [self.val] + res
        if self.right:
            res = self.right.path(k)
            if res:
                return [self.val] + res
        return []
Answered By: trincot