|
| 1 | +#User function Template for python3 |
| 2 | + |
| 3 | +class Solution: |
| 4 | +def __init__(self): |
| 5 | +self.max_sum=0 |
| 6 | +def maxPathSum(self, root): |
| 7 | +#code here |
| 8 | +temp=0 |
| 9 | +def helper(root,temp): |
| 10 | +if not root: |
| 11 | +return |
| 12 | +temp+=root.data |
| 13 | +if not root.left and not root.right: |
| 14 | +self.max_sum=max(self.max_sum,temp) |
| 15 | +helper(root.left,temp) |
| 16 | +helper(root.right,temp) |
| 17 | +helper(root,temp) |
| 18 | +return self.max_sum |
| 19 | + |
| 20 | + |
| 21 | +#{ |
| 22 | +# Driver Code Starts |
| 23 | +#Initial Template for Python 3 |
| 24 | + |
| 25 | + |
| 26 | +from collections import deque |
| 27 | +# Tree Node |
| 28 | +class Node: |
| 29 | +def __init__(self, val): |
| 30 | +self.right = None |
| 31 | +self.data = val |
| 32 | +self.left = None |
| 33 | + |
| 34 | +# Function to Build Tree |
| 35 | +def buildTree(s): |
| 36 | +#Corner Case |
| 37 | +if(len(s)==0 or s[0]=="N"): |
| 38 | +return None |
| 39 | + |
| 40 | +# Creating list of strings from input |
| 41 | +# string after spliting by space |
| 42 | +ip=list(map(str,s.split())) |
| 43 | + |
| 44 | +# Create the root of the tree |
| 45 | +root=Node(int(ip[0])) |
| 46 | +size=0 |
| 47 | +q=deque() |
| 48 | + |
| 49 | +# Push the root to the queue |
| 50 | +q.append(root) |
| 51 | +size=size+1 |
| 52 | + |
| 53 | +# Starting from the second element |
| 54 | +i=1 |
| 55 | +while(size>0 and i<len(ip)): |
| 56 | +# Get and remove the front of the queue |
| 57 | +currNode=q[0] |
| 58 | +q.popleft() |
| 59 | +size=size-1 |
| 60 | + |
| 61 | +# Get the current node's value from the string |
| 62 | +currVal=ip[i] |
| 63 | + |
| 64 | +# If the left child is not null |
| 65 | +if(currVal!="N"): |
| 66 | + |
| 67 | +# Create the left child for the current node |
| 68 | +currNode.left=Node(int(currVal)) |
| 69 | + |
| 70 | +# Push it to the queue |
| 71 | +q.append(currNode.left) |
| 72 | +size=size+1 |
| 73 | +# For the right child |
| 74 | +i=i+1 |
| 75 | +if(i>=len(ip)): |
| 76 | +break |
| 77 | +currVal=ip[i] |
| 78 | + |
| 79 | +# If the right child is not null |
| 80 | +if(currVal!="N"): |
| 81 | + |
| 82 | +# Create the right child for the current node |
| 83 | +currNode.right=Node(int(currVal)) |
| 84 | + |
| 85 | +# Push it to the queue |
| 86 | +q.append(currNode.right) |
| 87 | +size=size+1 |
| 88 | +i=i+1 |
| 89 | +return root |
| 90 | + |
| 91 | + |
| 92 | +if __name__=="__main__": |
| 93 | +t=int(input()) |
| 94 | +for _ in range(0,t): |
| 95 | +s=input() |
| 96 | +root=buildTree(s) |
| 97 | +ob= Solution() |
| 98 | + |
| 99 | +print(ob.maxPathSum(root)) |
| 100 | + |
| 101 | +# } Driver Code Ends |
0 commit comments