抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。

假设二叉树中至少有一个节点。


思路

  • 思路 1
    • 层序遍历,最后一层的第一个节点即为最后一层的最左边节点,因此记录遍历每层时的第一个节点。

学习点

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
// 层序遍历
// 记录遍历的每层的第一个
queue<TreeNode*> qe;
qe.push(root);
int first_of_layer = root->val;
while (!qe.empty())
{
int node_num = qe.size();
for (int i = 0; i < node_num; ++i)
{
TreeNode *tmp = qe.front();
qe.pop();

if (tmp->left)
qe.push(tmp->left);
if (tmp->right)
qe.push(tmp->right);

// 记录每层第一个
if (i == 0)
first_of_layer = tmp->val;
}
}

return first_of_layer;
}
};