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; } }};
阅读全文