513. Find Bottom Left Tree Value

来源:互联网 发布:淘宝专柜正品是真的吗 编辑:程序博客网 时间:2024/06/06 21:44

题目

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

Example 1:
Input:

  2 / \1   3

Output:
1
Example 2:
Input:

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

Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.

题意

找出一棵树最下面一层最左边的数.

分析

使用BFS, 对每一层保留第一个数, 直到结束.

实现

/** * 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) {        queue<TreeNode*> q;        q.push(root);        int last = root->val;        TreeNode *cur = root;        while (!q.empty()) {            int n = q.size();            last = (q.front())->val;            while (n--) {                cur = q.front();                if (cur->left) q.push(cur->left);                if (cur->right) q.push(cur->right);                q.pop();            }            if(q.empty())                return last;        }    }};
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 得了水痘要注意些什么 大人水痘图片初期 长水痘的前兆 水痘吃什么药 出水痘的症状及注意事项 儿童水痘图片 水痘多长时间能好 水痘用什么药膏 水痘结痂图片 水痘的预防措施有哪些 水痘初期症状图片 成人水痘的症状和自愈期 水痘可以吃什么 水痘和麻疹的区别 水痘可以吃什么水果 水痘是什么样的 水痘的症状和图片 水痘疫苗注意事项 如何预防水痘 水痘什么时候好 出水痘能吃什么 水痘一般几天能痊愈 宝宝出水痘要注意什么 水痘如何传染 出水痘能吹风吗 小孩出水痘的图片 水痘的传播途径 水痘会复发吗 成人出水痘几天能好 生水痘的症状 水痘能不能洗澡 水痘多久能好 孩子出水痘怎么护理 起水痘的原因 水痘的传播途径是什么 出水痘几天能好 水痘可以洗澡吗 水痘长什么样 水痘传播途径 水痘疫苗多少钱 得水痘不能玩手机