解法1:递归法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxLen = INT_MIN;
int maxleftvalue;
void traversal(TreeNode* root, int leftLen){
if(root->left == NULL && root->right == NULL){
if(leftLen > maxLen){
maxLen = leftLen;
maxleftvalue = root->val;
}
return;
}
if(root->left){
leftLen++;
traversal(root->left,leftLen);
leftLen--;
}
if(root->right){
leftLen++;
traversal(root->right,leftLen);
leftLen--;
}
return;
}
int findBottomLeftValue(TreeNode* root) {
traversal(root,0);
return maxleftvalue;
}
};
解法2:层序遍历法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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;
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return result;
}
};