DAY 18
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
vector<int> res;
queue<TreeNode*> q;
q.push(root);
int num = 0 ;
while(q.size())
{
int len = q.size();
for(int i = 0;i < len;i++)
{
auto t = q.front();
if(i == 0) num = t->val;;
q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
return num;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> res;
vector<int> num;
void dfs(TreeNode* root)
{
res.push_back(root->val);
if(!root->left && !root->right)
{
int sum = res[0];
for(int i = 1;i < res.size();i++)
{
sum += res[i];
}
num.push_back(sum);
}
else
{
if(root->left)
{
dfs(root->left);
res.pop_back();
}
if(root->right)
{
dfs(root->right);
res.pop_back();
}
}
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(!root) return 0;
dfs(root);
// for(int i = 0;i < num.size();i++)
// {
// if(targetSum == num[i]) return true;
// else return false;
// }
// return false;
auto result = find(num.begin( ), num.end( ), targetSum); //查找1
if ( result == num.end( ) ) //没找到
return false;
else //找到
return true;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_map<int,int> pos;
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
for(int i = 0;i < inorder.size();i++) pos[inorder[i]] = i;
return dfs(inorder,postorder,0,inorder.size() - 1,0,postorder.size() - 1);
}
TreeNode* dfs(vector<int>& inorder, vector<int>& postorder,int il,int ir,int pl,int pr)
{
//判断条件不加会导致溢出
if(il > ir ) return NULL;
//根节点为后续遍历的最后一个点
auto root = new TreeNode(postorder[pr]);
//找出根节点在中序遍历中的位置
int k = pos[root->val];
//按照中序遍历根节所在位置点左边为二叉树左子树,右为二叉树右子树来查找
root->left = dfs(inorder,postorder,il,k - 1,pl,pl + k - 1 - il);
root->right = dfs(inorder,postorder,k + 1,ir,pl + k -il,pr - 1); // 根节点要丢掉
return root;
}
};