【算法分析与设计】【第十五周】513. Find Bottom Left Tree Value

本文介绍了解决LeetCode 513题“寻找二叉树最底层最左边的值”的方法。通过广度优先搜索(BFS)实现层次遍历,详细解释了如何记录每一层的节点数并获取最底层最左侧元素的值。

题目来源:513. https://leetcode.com/problems/find-bottom-left-tree-value/description/

BFS基础训练。二叉树层次遍历,记录每一层。

513. Find Bottom Left Tree Value

题目大意

找出二叉树最底层最左边的元素的值。

Example 1:
Input:

 2
/ \
1 3

Output:
1

Example 2:
Input:

    1
   / \
  2   3
 /   / \
4   5   6
   /
  7

Output:
7

思路

利用bfs实现层次遍历,非常经典了。
难度主要在记录二叉树的层数,friendbkf讲得相当清晰。

我复述一遍:
通过两个计数器curLevelCountnextLevelCount 分别记录当前层的节点数和下一层的结点数。
每当有一个结点被弹出队列时,curLevelCount计数器就减一;每当有一个结点入队时,nextLevelCount 加一。
直到curLevelCount为0,表示该层所有结点都已经搜索完毕,则将nextLevelCount值赋给curLevelCount,进行下一层的搜索,接着不要忘了将nextLevelCount置为0。
记录每一层最先出队的元素的值,并在进入下一层时更换,最后得到的就是最底层最左边的元素的值。

解题代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        int bottomLeftValue;
        vector<int> values;
        if (root == NULL) return 0;
        queue<TreeNode*> myq;
        myq.push(root);
        int curLevelCount = 1;
        int nextLevelCount = 0;
        TreeNode* temp;
        int levelCount = 0;
        while (!myq.empty()) {
            temp = myq.front();
            myq.pop();
            values.push_back(temp->val);
            curLevelCount--;
            if (temp->left != NULL) {
                nextLevelCount++;
                myq.push(temp->left);
            }
            if (temp->right != NULL) {
                nextLevelCount++;
                myq.push(temp->right);
            }
            if (curLevelCount == 0) {
                curLevelCount = nextLevelCount;
                nextLevelCount = 0;
                levelCount++;
                bottomLeftValue = values[0];
                values.clear();
            }   
        }
        return bottomLeftValue;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值