題目來源:https://leetcode.cn/problems/find-bottom-left-tree-value/description/
C++題解1:是尋找最底層最左邊的節(jié)點(diǎn),不是最底層的左子樹節(jié)點(diǎn)!?!
使用層序遍歷,判斷左右子樹是不是葉子節(jié)點(diǎn),進(jìn)而判斷是不是該層的最左邊節(jié)點(diǎn),用flg來標(biāo)記,所以flg需要在每一層開始時(shí)進(jìn)行更新。文章來源:http://www.zghlxwxcb.cn/news/detail-508568.html
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> que;
if (root != NULL) que.push(root);
int result = 0;
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
if (i == 0) result = node->val; // 記錄最后一行第一個(gè)元素
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return result;
}
};
C++題解2(來源代碼隨想錄):遞歸法,尋求最大深度的葉子節(jié)點(diǎn),前序遍歷。文章來源地址http://www.zghlxwxcb.cn/news/detail-508568.html
class Solution {
public:
int maxDepth = INT_MIN;
int result;
void traversal(TreeNode* root, int depth) {
if (root->left == NULL && root->right == NULL) {
if (depth > maxDepth) {
maxDepth = depth;
result = root->val;
}
return;
}
if (root->left) {
traversal(root->left, depth + 1); // 隱藏著回溯
}
if (root->right) {
traversal(root->right, depth + 1); // 隱藏著回溯
}
return;
}
int findBottomLeftValue(TreeNode* root) {
traversal(root, 0);
return result;
}
};
到了這里,關(guān)于力扣 513. 找樹左下角的值的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!