Fork me on GitHub

Find Bottom Left Tree Value

Description

https://leetcode.com/problems/find-bottom-left-tree-value/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
map<int, int> depthMapping;
int depth = 0;
helper(root, depthMapping, depth);
return depthMapping.rbegin()->second;
}

void helper(TreeNode* root, map<int, int>& depthMapping, int depth) {
if (root == NULL) return;
helper(root->left, depthMapping, depth + 1);
auto iter = depthMapping.find(depth);
if(iter == depthMapping.end()) depthMapping[depth] = root->val;
helper(root->right, depthMapping, depth + 1);
return;
}
};