LeetCode Algorithm部分.513
【513】 Find Bottom Left Tree Value
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input:
2
/ \
1 3Output:
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) {
vector<TreeNode*> nq,nqa;
if((root->left==NULL) && (root->right==NULL)) nqa.push_back(root);
if(root->left!=NULL) nq.push_back(root->left);
if(root->right!=NULL) nq.push_back(root->right);
while(!nq.empty()){
nqa = nq;
nq.clear();
for(int i = 0; i < nqa.size();i++){
if(nqa[i]->left!=NULL) nq.push_back(nqa[i]->left);
if(nqa[i]->right!=NULL) nq.push_back(nqa[i]->right);
}
}
return nqa[0]->val;
}
};