题目:
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.
解读:给予一颗二叉树,找到最深的节点中最左边的那个并输出val值。
思考:采用BFS层次遍历算法,为使的最后的结果输出的是最左边的节点,则queue先push右节点再push左节点。
代码:
/**
* 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;
int answer;
if(root != NULL)
q.push(root);
while(q.size()){
if(q.front()->right !=NULL)
q.push(q.front()->right);
if(q.front()->left !=NULL)
q.push(q.front()->left);
answer = q.front()->val;
q.pop();
}
return answer;
}
};
本文介绍了一种算法来寻找给定二叉树中最底层最左边节点的值。通过采用一种特殊的BFS层次遍历方法,该算法能够确保找到目标节点,并给出了一段C++实现代码。
1584

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



