513. 找树左下角的值(BFS)

给定一个二叉树,在树的最后一行找到最左边的值。

分析:

BFS一层层找,每次去记录遍历的当前层的第一个节点的值,因为要的是最左边的值

PS:BFS的模板,先初始化一个队列,把根节点push到队列中,然后外层while()判断条件为队列不为空,进入while每次先获取队列长度,将长度作为内部for循环的执行次数,实现对每一层的每一个节点的左右孩子情况的判断,在遍历每个节点的同时去完成一些题目中的要求,比如记录一些数据,计算一些数据等。

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;
    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_34612223/article/details/113831875