BFS
開始做BFS的題目, 題目鏈接: https://leetcode-cn.com/problems/find-bottom-left-tree-value/
1. 想到的是標記層數,記錄最新一層的的第一個,最後一次記錄即爲需要的。
/**
* 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) {
queue<TreeNode*> work;
work.push(root);
map<TreeNode*, int> dis;
dis[root] = 0;
int cur = 0;
int ans = root->val;
while (!work.empty()) {
TreeNode* tmp = work.front();
work.pop();
if (dis[tmp] != cur) {
ans = tmp->val;
cur = dis[tmp];
}
if (tmp->left != nullptr) {
work.push(tmp->left);
dis[tmp->left] = dis[tmp] + 1;
}
if (tmp->right != nullptr) {
work.push(tmp->right);
dis[tmp->right] = dis[tmp] + 1;
}
}
return ans;
}
};
2. 參考評論代碼,從右往左遍歷,最後一個即爲需要的。
/**
* 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) {
queue<TreeNode*> work;
work.push(root);
TreeNode* ans = root;
while (!work.empty()) {
ans = work.front();
work.pop();
if (ans->right != nullptr) {
work.push(ans->right);
}
if (ans->left != nullptr) {
work.push(ans->left);
}
}
return ans->val;
}
};