File size: 2,158 Bytes
3c88a0f | 1 2 3 4 5 | {"type": "session", "harness": "opencode", "id": "cp-10020", "name": "LeetCode 0513: Find Bottom Left Tree Value"}
{"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 Bottom Left Tree Value (Difficulty: Medium)\nTags: Tree, Depth-First Search, Breadth-First Search, Binary Tree\n\nGiven the root of a binary tree, return the leftmost value in the last row of the tree.\n\nExample 1:\nInput: root = [2,1,3]\nOutput: 1\n\nExample 2:\nInput: root = [1,2,3,4,null,5,6,null,null,7]\nOutput: 7\n\nConstraints:\n- The number of nodes in the tree is in the range [1, 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 findBottomLeftValue(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n def findBottomLeftValueHelper(root, curr_depth, max_depth, bottom_left_value):\n if not root:\n return max_depth, bottom_left_value\n if not root.left and not root.right and curr_depth+1 > max_depth:\n return curr_depth+1, root.val\n max_depth, bottom_left_value = findBottomLeftValueHelper(root.left, curr_depth+1, max_depth, bottom_left_value)\n max_depth, bottom_left_value = findBottomLeftValueHelper(root.right, curr_depth+1, max_depth, bottom_left_value)\n return max_depth, bottom_left_value\n\n result, max_depth = 0, 0\n return findBottomLeftValueHelper(root, 0, max_depth, result)[1]\n\n\n# Time: O(n)\n# Space: O()\nimport collections\n\n\nclass Solution2(object):\n def findBottomLeftValue(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n last_node, q = None, collections.deque([root])\n while q:\n last_node = q.popleft()\n q.extend([n for n in [last_node.right, last_node.left] if n])\n return last_node.val\n\n"}}
|