I have to obtain all the root-to-leaf paths in a binary tree. Now this is usually an easy task, but now I have to identify the left and right nodes as well. That is, when I'm going into a node's left subtree, the node should be recorded in the path as !abc, where abc is node name. When going into the right subtree, the node should be recorded as is. So if my tree is 1(left)2 (right)3, then the two paths that must be saved are !1->2 and 1->3. This is my code:
def get_tree_path(root, paths, treepath):
if not root:
if not root.left and not root.right:
get_tree_path(root.left, paths, treepath)
get_tree_path(root.right, paths, treepath)
This does obtain the paths. But the left and right subtree paths are all joined together. That is, for the example given above, I get [!1, 3, 1, 2] as output. I have tried many suggestions given here: print all root to leaf paths in a binary tree and binary search tree path list but I'm only getting more errors. Please help.