|
| 1 | +# Time: O(n) |
| 2 | +# Space: O(h) |
| 3 | + |
| 4 | +# Given a binary tree, find the leftmost value in the last row of the tree. |
| 5 | +# |
| 6 | +# Example 1: |
| 7 | +# Input: |
| 8 | +# |
| 9 | +# 2 |
| 10 | +# / \ |
| 11 | +# 1 3 |
| 12 | +# |
| 13 | +# Output: |
| 14 | +# 1 |
| 15 | +# Example 2: |
| 16 | +# Input: |
| 17 | +# |
| 18 | +# 1 |
| 19 | +# / \ |
| 20 | +# 2 3 |
| 21 | +# / / \ |
| 22 | +# 4 5 6 |
| 23 | +# / |
| 24 | +# 7 |
| 25 | +# |
| 26 | +# Output: |
| 27 | +# 7 |
| 28 | +# Note: You may assume the tree (i.e., the given root node) is not NULL. |
| 29 | + |
| 30 | +# Definition for a binary tree node. |
| 31 | +# class TreeNode(object): |
| 32 | +# def __init__(self, x): |
| 33 | +# self.val = x |
| 34 | +# self.left = None |
| 35 | +# self.right = None |
| 36 | + |
| 37 | +class Solution(object): |
| 38 | + def findBottomLeftValue(self, root): |
| 39 | + """ |
| 40 | + :type root: TreeNode |
| 41 | + :rtype: int |
| 42 | + """ |
| 43 | + def findBottomLeftValueHelper(root, curr_depth, max_depth, bottom_left_value): |
| 44 | + if not root: |
| 45 | + return max_depth, bottom_left_value |
| 46 | + if not root.left and not root.right and curr_depth+1 > max_depth: |
| 47 | + return curr_depth+1, root.val |
| 48 | + max_depth, bottom_left_value = findBottomLeftValueHelper(root.left, curr_depth+1, max_depth, bottom_left_value) |
| 49 | + max_depth, bottom_left_value = findBottomLeftValueHelper(root.right, curr_depth+1, max_depth, bottom_left_value) |
| 50 | + return max_depth, bottom_left_value |
| 51 | + |
| 52 | + result, max_depth = 0, 0 |
| 53 | + return findBottomLeftValueHelper(root, 0, max_depth, result)[1] |
| 54 | + |
| 55 | + |
| 56 | +# Time: O(n) |
| 57 | +# Space: O(n) |
| 58 | +class Solution2(object): |
| 59 | + def findBottomLeftValue(self, root): |
| 60 | + """ |
| 61 | + :type root: TreeNode |
| 62 | + :rtype: int |
| 63 | + """ |
| 64 | + queue = [root] |
| 65 | + for node in queue: |
| 66 | + queue += filter(None, (node.right, node.left)) |
| 67 | + return node.val |
0 commit comments