題目
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input: 2 / \ 1 3 Output: 1
Example 2:
Input: 1 / \ 2 3 / / \ 4 5 6 / 7 Output: 7
Note: You may assume the tree (i.e., the given root node) is not NULL.
解題思路
找到樹的最底層,然後返回最左邊的數值。
代碼
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
vector<TreeNode*> save, save2;
save.push_back(root);
while (1) {
for(int i = 0; i < save.size(); i++) {
if (save[i]->left != NULL) save2.push_back(save[i]->left);
if (save[i]->right != NULL) save2.push_back(save[i]->right);
}
if (save2.size() == 0) {
return save[0]->val;
}
else {
save = save2;
save2.clear();
}
}
}
};
感想
忘了把save2清空,debug了好久……