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

来源:互联网 发布:里德学院知乎 编辑:程序博客网 时间:2024/06/14 10:47

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

  • Find Bottom Left Tree Value
    • 题目大意
    • 思路
    • 解题代码

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;    }};
原创粉丝点击