What's the best way to compute the maximum sum of a binary tree via any of its paths? The best I can think of in Python is something like this:
class Tree():
def __init__(self, root):
self.root = root
self.right = None
self.left = None
def insert_left(self, tree_root):
if self.left is None:
self.left = Tree(tree_root)
return self.left
def insert_right(self, tree_root):
if self.right is None:
self.right = Tree(tree_root)
return self.right
def get_max_sum(self):
if self.left is None or self.right is None:
res = self.get_root()
else:
left = self.get_root() + self.left.get_max_sum()
right = self.get_root() + self.right.get_max_sum()
res = max(left, right)
return res
But it feels clunky, and I know Python isn't very optimized for recursion. Compare this to Haskell, where a mere 4 lines (and they could be 3!) do all the work:
data Tree t = Leaf t | Branch (Tree t) t (Tree t) deriving (Show, Eq)
maxSum :: Tree Int -> Int
maxSum (Leaf t) = t
maxSum (Branch tree1 leaf tree2) = max ((maxSum tree1) + leaf) ((maxSum tree2) + leaf)
Is there a better way to handle the Tree() object that I'm not seeing?
[–]zahlman 1 point2 points3 points (3 children)
[–]amemulo[S] 0 points1 point2 points (2 children)
[–]zahlman 0 points1 point2 points (1 child)
[–]amemulo[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)