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 notNULL.
思路:广度优先遍历,需要知道每一层的最左边的数
知识点:queue.empty(); queue.push(); queue.front(); queue.pop(); 初始化一个空队列spson=queue<TreeNode*>();
代码1:
/**
* 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*> store;
vector<int> pos;
int count=0,i=0;
pos.push_back(0);
store.push_back(root);
while(count<store.size()){
if(count==(pos[i])){
if(store[count]->left != NULL){store.push_back(store[count]->left);}
if(store[count]->right != NULL){store.push_back(store[count]->right);}
pos.push_back(store.size()-1);
count++;
i++;
}
else{
if(store[count]->left != NULL){store.push_back(store[count]->left);}
if(store[count]->right != NULL){store.push_back(store[count]->right);}
count++;
}
}
if(pos.size()<3) {return root->val;}
return store[pos[i-2]+1]->val;
}
};
代码2:
/**
* 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*> sp,spson;
TreeNode* res=root;
sp.push(root);
while(!sp.empty()){
TreeNode* temp;
temp=sp.front();
sp.pop();
if(temp->left!=NULL){spson.push(temp->left);}
if(temp->right!=NULL){spson.push(temp->right);}
if(sp.empty()){
sp=spson;
if(!spson.empty()){res=spson.front();}
spson=queue<TreeNode*>();
}
}
return res->val;
}
};
利用spson存储前一层所有节点的子节点,所以front就是该层最左边的数
代码3:
class Solution {
public:
void findBottomLeftValue(TreeNode* root, int& maxDepth, int& leftVal, int depth) {
if (root == NULL) {
return;
}
//Go to the left and right of each node
findBottomLeftValue(root->left, maxDepth, leftVal, depth+1);
findBottomLeftValue(root->right, maxDepth, leftVal, depth+1);
//Update leftVal and maxDepth
if (depth > maxDepth) {
maxDepth = depth;
leftVal = root->val;
}
}
//Entry function
int findBottomLeftValue(TreeNode* root) {
int maxDepth = 0;
//Initialize leftVal with root's value to cover the edge case with single node
int leftVal = root->val;
findBottomLeftValue(root, maxDepth, leftVal, 0);
return leftVal;
}
};
最后一段还没看