代码随想录:找树左下角的值
层次遍历轻轻松松
/*** 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) {if (!root)return 0;queue<TreeNode*> que;que.push(root);while (!que.empty()) {int this_left;int next_size = 0;int size = que.size();for (int i = 0; i < size; i++) {TreeNode* target = que.front();que.pop();if (i == 0)this_left = target->val;if (target->left) {que.push(target->left);next_size++;}if (target->right) {que.push(target->right);next_size++;}}if (next_size == 0)return this_left;}return 0;}
};