【刷题日记】二叉树-找树左下角的值-L513-Medium
给定一个二叉树的 根节点 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; } };
|