I’m preparing interviews and studying BST tree.
Maximum Sum Path Given a binary tree consisting of nodes with positive integer values, write a method – max_sum_path that returns the maximum sum of data values obtained by traversing nodes along a path between any 2 nodes of the tree. The path must originate and terminate at 2 different nodes of the tree, and the maximum sum is obtained by summing all the data values of the nodes traversed along this path.
1 / \
2 3 => 18 / \ / \ 4 5 6 7
Path: 5 -> 2 -> 1 -> 3 -> 7 Max Sum = 5+2+1+3+7 = 18
Given the class Node
class Node: def __init__(self): self.data = None self.next = None def setData(self,data): self.data = data def getData(self): return self.data def setNext(self,next): self.next = next # solution #1 class SinglyLinkedList: #constructor def __init__(self): self.head = None #method for setting the head of the Linked List def setHead(self,head): self.head = head def is_cyclic(self): slow = self.head fast = self.head while slow and fast and fast.getNext(): slow = slow.getNext() fast = fast.getNext().getNext() if fast == slow: return True return False
This is using the runner approach by having slow move by one while fast moves by two. Sooner or later, they will meet if there is a cycle somewhere. If not, then the while condition will fail meaning the end was hit with “None” and it will return false.
# alternative solution 2 class BinaryTree: def __init__(self, root_node = None): self.root = root_node maxSum = float("-inf") def recMax(self, root): if root is None: return 0 left_sum = max(0, self.recMax(root.left_child)) right_sum = max(0, self.recMax(root.right_child)) self.maxSum = max(self.maxSum, root.data + left_sum + right_sum) return root.data + max(left_sum, right_sum) # All the necessary collection moduled have been already imported. def max_sum_path(self,root): if root is None: return 0 self.recMax(root) return self.maxSum
✓ Extra quality
ExtraProxies brings the best proxy quality for you with our private and reliable proxies
✓ Extra anonymity
Top level of anonymity and 100% safe proxies – this is what you get with every proxy package
✓ Extra speed
1,ooo mb/s proxy servers speed – we are way better than others – just enjoy our proxies!
USA proxy location
We offer premium quality USA private proxies – the most essential proxies you can ever want from USA
99,9% servers uptime
No usage restrictions
Perfect for SEO
We are working 24/7 to bring the best proxy experience for you – we are glad to help and assist you!