您的位置:首页 > 产品设计 > UI/UE

LeetCode 513 Find Bottom Left Tree Value(二叉树层序遍历)

2017-07-19 19:49 597 查看
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.

题目大意:给出一棵二叉树,求这棵树最底层最左边的节点值。

解题思路:又是一道层序遍历可以做的题。用数组保存每一层的第一个元素,最后返回数组中最后一个元素即可。

代码如下:

/**
* 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) {
levelOrderTraversal(root, 0, ans);
return ans.back();
}
private:
queue<TreeNode*> que;
vector<int> ans;

//非递归版本
void levelOrderTraversal(TreeNode* root, vector<int>& ans) {
if(root == nullptr) return ;
TreeNode* tmp;
que.push(root);
int cur = 0;
while(cur < que.size()) {
int last = que.size();
tmp = que.front();
ans.push_back(tmp->val);
while(cur < last) {
tmp = que.front();
que.pop();
if(tmp->left) que.push(tmp->left);
if(tmp->right) que.push(tmp->right);
cur++;
}
cur = 0;
}
}

//递归版本
void levelOrderTraversal(TreeNode* root, int depth, vector<int>& ans) {
if(root == nullptr) return ;
if(depth == ans.size()) ans.push_back(root->val);
if(root->left) levelOrderTraversal(root->left, depth + 1, ans);
if(root->right) levelOrderTraversal(root->right, depth + 1, ans);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息