Skip to content
Advertisement

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

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

JavaScript

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:

JavaScript

Advertisement

Answer

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:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement