您的当前位置:首页【算法分析与设计】【第十五周】513. Find Bottom Left Tree Value

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

来源:锐游网

题目来源:513.

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

513. Find Bottom Left Tree Value

题目大意

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

思路

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

我复述一遍:
通过两个计数器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;
    }
};

因篇幅问题不能全部显示,请点此查看更多更全内容

Top