|
| 1 | +# 513. Find Bottom Left Tree Value |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree. |
| 5 | +- Similar Questions: . |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Given the `root` of a binary tree, return the leftmost value in the last row of the tree. |
| 10 | + |
| 11 | + |
| 12 | +Example 1: |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +``` |
| 17 | +Input: root = [2,1,3] |
| 18 | +Output: 1 |
| 19 | +``` |
| 20 | + |
| 21 | +Example 2: |
| 22 | + |
| 23 | + |
| 24 | + |
| 25 | +``` |
| 26 | +Input: root = [1,2,3,4,null,5,6,null,null,7] |
| 27 | +Output: 7 |
| 28 | +``` |
| 29 | + |
| 30 | + |
| 31 | +**Constraints:** |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | +- The number of nodes in the tree is in the range `[1, 104]`. |
| 36 | + |
| 37 | +- `-231 <= Node.val <= 231 - 1` |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | +## Solution |
| 42 | + |
| 43 | +```javascript |
| 44 | +/** |
| 45 | + * Definition for a binary tree node. |
| 46 | + * function TreeNode(val, left, right) { |
| 47 | + * this.val = (val===undefined ? 0 : val) |
| 48 | + * this.left = (left===undefined ? null : left) |
| 49 | + * this.right = (right===undefined ? null : right) |
| 50 | + * } |
| 51 | + */ |
| 52 | +/** |
| 53 | + * @param {TreeNode} root |
| 54 | + * @return {number} |
| 55 | + */ |
| 56 | +var findBottomLeftValue = function(root) { |
| 57 | + return dfs(root, 0)[0]; |
| 58 | +}; |
| 59 | + |
| 60 | +var dfs = function(node, depth) { |
| 61 | + var left = node.left ? dfs(node.left, depth + 1) : [node.val, depth]; |
| 62 | + var right = node.right ? dfs(node.right, depth + 1) : [node.val, depth]; |
| 63 | + return right[1] > left[1] ? right : left; |
| 64 | +}; |
| 65 | +``` |
| 66 | + |
| 67 | +**Explain:** |
| 68 | + |
| 69 | +nope. |
| 70 | + |
| 71 | +**Complexity:** |
| 72 | + |
| 73 | +* Time complexity : O(n). |
| 74 | +* Space complexity : O(1). |
0 commit comments