Here's a working implementation:
class Node: def __init__(self, x): self.val = x self.left = None self.right = None def print_path(root): rightpath = [] leftpath = [] path = [] if root is None: return [] if (root.right is None) and (root.left is None): return [root.val] elif root.right is not None: rightpath = [root.val] + print_path(root.right) elif root.left is not None: leftpath = [root.val] + print_path(root.left) return argmax(rightpath, leftpath) def argmax(lst1, lst2): return lst1 if len(lst1) > len(lst2) else lst2 root_node = Node('a') root_node.left = Node('b') root_node.right = Node('c') root_node.right.right = Node('f') print print_path(root_node)
A couple of problems with your code:
1) checking root.left is None before (root.right is None) and (root.left is None) is incorrect - you will never reach (root.right is None) and (root.left is None)
2) instead of returning immediately, you want to use recursion and compare both branches, and then return the branch with the longest path.
3) append added in place, so you need to save it in a variable
Edit: Pure implementation (see comments)
class Node: def __init__(self, x): self.val = x self.left = None self.right = None def print_path(root): rightpath = [] leftpath = [] path = [] if root is None: return [] rightpath = [root.val] + print_path(root.right) leftpath = [root.val] + print_path(root.left) return argmax(rightpath, leftpath) def argmax(lst1, lst2): return lst1 if len(lst1) > len(lst2) else lst2 root_node = Node('a') root_node.left = Node('b') root_node.right = Node('c') root_node.right.right = Node('f') print print_path(root_node)
source share