tinycodinglm / cp /cp-10044.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
1.96 kB
{"type": "session", "harness": "opencode", "id": "cp-10044", "name": "LeetCode 0538: Convert Bst To Greater Tree"}
{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}
{"type": "message", "message": {"role": "user", "content": "Problem: Convert BST to Greater Tree (Difficulty: Medium)\nTags: Tree, Depth-First Search, Binary Search Tree, Binary Tree\n\nGiven the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.\nAs a reminder, a binary search tree is a tree that satisfies these constraints:\nNote: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/\n\nExample 1:\nInput: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\nOutput: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\n\nExample 2:\nInput: root = [0,null,1]\nOutput: [1,null,1]\n\nConstraints:\n- The number of nodes in the tree is in the range [0, 104].\n- -10^4 <= Node.val <= 10^4\n- All the values in the tree are unique.\n- root is guaranteed to be a valid binary search tree."}}
{"type": "message", "message": {"role": "assistant", "content": "# Time: O(n)\n# Space: O(h)\n\nclass Solution(object):\n def convertBST(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n def convertBSTHelper(root, cur_sum):\n if not root:\n return cur_sum\n\n if root.right:\n cur_sum = convertBSTHelper(root.right, cur_sum)\n cur_sum += root.val\n root.val = cur_sum\n if root.left:\n cur_sum = convertBSTHelper(root.left, cur_sum)\n return cur_sum\n\n convertBSTHelper(root, 0)\n return root\n\n"}}