513. 找树左下角的值
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-bottom-left-tree-value
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
示例 1:
输入: root = [2,1,3]
输出: 1
示例 2:
输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7
提示:
- 二叉树的节点个数的范围是 [1,104]
- -231 <= Node.val <= 231 - 1
题目分析
- 根据题目描述获取树最底层最左边的节点
- 广度优先搜索遍历,当遍历到最后一层时,第一个节点即为所求
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
TreeNode* node = root;
queue<TreeNode*> nodeList;
nodeList.emplace(root);
while (!nodeList.empty()) {
int nodeListLen = nodeList.size();
node = nodeList.front();
for (int i = 0; i < nodeListLen; ++i) {
if (nodeList.front()->left) nodeList.emplace(nodeList.front()->left);
if (nodeList.front()->right) nodeList.emplace(nodeList.front()->right);
nodeList.pop();
}
}
return node->val;
}
};