513. Find Bottom Left Tree Value

来源:互联网 发布:课堂教学互动软件 编辑:程序博客网 时间:2024/05/16 09:29

Find Bottom Left Tree Value

描述

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的基础题。
做bfs的思路就是:
1.遍历某一层的结点,同时用queue保存得到的下层结点;
2.用某种方式记录当前层遍历结束后,开始遍历下层结点;
3.依此类推。

/** * 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 rlt;        queue<TreeNode*> nodes;        nodes.push(root);        while(!nodes.empty())        {            int _size=nodes.size();            rlt=nodes.front()->val;            while (_size)            {                TreeNode* tmp=nodes.front();                nodes.pop();                if (tmp->left)                {                    nodes.push(tmp->left);                }                if (tmp->right)                {                    nodes.push(tmp->right);                }                _size--;            }        }        return rlt;    }};
0 0