Skip to content

Instantly share code, notes, and snippets.

@parcar
Created August 15, 2019 20:29
Show Gist options
  • Select an option

  • Save parcar/d744f98838e82e65337eb5f1de26bd11 to your computer and use it in GitHub Desktop.

Select an option

Save parcar/d744f98838e82e65337eb5f1de26bd11 to your computer and use it in GitHub Desktop.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def bstToGst(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if(root is None):
return
ms = []
total = 0
curr = root
#Do reverse inorder traversal
while(len(ms) or curr is not None):
if (curr is not None):
ms.append(curr)
curr = curr.right
else:
curr = ms.pop()
#Maintain an int total, updating each node
#With total + val as we descend in value
total += curr.val
curr.val = total
curr = curr.left
return root
'''
Runtime: 20 ms, faster than 52.02% of Python online submissions for Binary Search Tree to Greater Sum Tree.
Memory Usage: 11.8 MB, less than 100.00% of Python online submissions for Binary Search Tree to Greater Sum Tree.
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment