-
-
Save parcar/d744f98838e82e65337eb5f1de26bd11 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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