513. Find the value of the lower left corner of the tree (BFS)

Given a binary tree, find the leftmost value in the last row of the tree.

analysis:

BFS finds layer by layer, every time it records the value of the first node of the current layer traversed, because it wants the leftmost value

PS: BFS template, first initialize a queue, push the root node to the queue, and then the outer while() judges that the queue is not empty. Each time you enter while, the queue length is obtained first, and the length is used as the execution of the inner for loop. The number of times, to realize the judgment of the left and right children of each node of each layer, and to complete the requirements in some questions while traversing each node, such as recording some data, calculating some data, etc.

class Solution {
    
    
public:
    int findBottomLeftValue(TreeNode* root) {
    
    
        queue<TreeNode*> q;
        int leftResult = 0;
        if (root == nullptr) return 0;
        q.push(root);
        while (!q.empty()){
    
    
            int size = q.size();
            for (int i = 0; i < size; i++){
    
    
                TreeNode* node = q.front();
                q.pop();
                if (i == 0) leftResult = node->val;
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
        }
        return leftResult;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_34612223/article/details/113831875