File size: 1,980 Bytes
3c88a0f
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "cp-10022", "name": "LeetCode 0515: Find Largest Value In Each Tree Row"}
{"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: Find Largest Value in Each Tree Row (Difficulty: Medium)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).\n\nExample 1:\nInput: root = [1,3,2,5,3,null,9]\nOutput: [1,3,9]\n\nExample 2:\nInput: root = [1,2,3]\nOutput: [1,3]\n\nConstraints:\n- The number of nodes in the tree will be in the range [0, 104].\n- -2^31 <= Node.val <= 2^31 - 1"}}
{"type": "message", "message": {"role": "assistant", "content": "# Time:  O(n)\n# Space: O(h)\n\nclass Solution(object):\n    def largestValues(self, root):\n        \"\"\"\n        :type root: TreeNode\n        :rtype: List[int]\n        \"\"\"\n        def largestValuesHelper(root, depth, result):\n            if not root:\n                return\n            if depth == len(result):\n                result.append(root.val)\n            else:\n                result[depth] = max(result[depth], root.val)\n            largestValuesHelper(root.left, depth+1, result)\n            largestValuesHelper(root.right, depth+1, result)\n\n        result = []\n        largestValuesHelper(root, 0, result)\n        return result\n\n\n# Time:  O(n)\n# Space: O(n)\nclass Solution2(object):\n    def largestValues(self, root):\n        \"\"\"\n        :type root: TreeNode\n        :rtype: List[int]\n        \"\"\"\n        result = []\n        curr = [root]\n        while any(curr):\n            result.append(max(node.val for node in curr))\n            curr = [child for node in curr for child in (node.left, node.right) if child]\n        return result\n\n\n"}}