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.
Subscribe to see which companies asked this question.
题目分析:
1、根据题干,题目要求计算一颗树的底部(左侧)的值,也就是找到深度最大的叶节点,若存在多个,则取最左边的。
2、BFS算法:BFS在本题中显然比DFS更适合,因为它不需要DFS中单独记录之前的判断信息,判断过程也更加简单。具体实现由Queue完成,BFS也可以理解为层序遍历,我们只需要将常规的层序遍历稍加改动,即每层从右端开始push即可,这样整个BFS完成的时候最后一个元素即为所求的结点,返回其val即可。此题采用BFS。
代码
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
- * };
- */
- #include<queue>
- class Solution {
- public:
- int findBottomLeftValue(TreeNode* root) {
- queue<TreeNode*> Q;
- Q.push(root);
- int ans;
- while(Q.size()){
- if(Q.front()->right != NULL)
- Q.push(Q.front()->right);
- if(Q.front()->left != NULL)
- Q.push(Q.front()->left);
- ans = Q.front()->val;
- Q.pop();
- }
- return ans;
- }
- };
本文介绍了一种使用BFS算法寻找二叉树最深最左叶子节点值的方法,并提供了一个具体的C++实现示例。

565

被折叠的 条评论
为什么被折叠?



