给定一棵二叉树,找到这棵树最中最后一行中最左边的值。
样例
样例1:
输入:{2,1,3}
输出:1
解释:
2
/ \
1 3
样例2:
输人:{1,2,3,4,5,6,#,#,7}
输出:7
解释:
1
/ \
2 3
/ \ /
4 5 6
\
7
注意事项
你可以假设树(即给定的根节点)不是NULL。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a root of tree
* @return: return a integer
*/
int findBottomLeftValue(TreeNode * root) {
// write your code here
vector<vector<int>> result;
if (root == NULL) {
return -1;
}
queue<TreeNode *> Q;
Q.push(root);
while (!Q.empty()) {
int size = Q.size();
vector<int> level;
for (int i = 0; i < size; i++) {
TreeNode *head = Q.front(); Q.pop();
level.push_back(head->val);
if (head->left != NULL) {
Q.push(head->left);
}
if (head->right != NULL) {
Q.push(head->right);
}
}
result.push_back(level);
}
return result[result.size()-1][0];
}
};