513.找树左下角的值
踩坑了:因为要的是最底层最左边,而不一定是左叶子。前中后序无所谓,因为对中节点不做处理,一层中一定是第一个元素的depth被更新,左边优先遍历。一层中没有左节点就会使某个右节点成为相对靠左的节点
递归:
/**
* 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 maxdepth = INT_MIN;
int res = 0;
int findBottomLeftValue(TreeNode* root) {
findLeft(root,1);
return res;
}
void findLeft(TreeNode* cur, int depth){
if(cur->left == nullptr && cur->right == nullptr){
if(depth > maxdepth){
maxdepth = depth;
res = cur->val;
}
return;
}
if(cur->left) findLeft(cur->left, depth+1);
if(cur->right) findLeft(cur->right,depth+1);
}
};
层序:
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> que;
que.push(root);
int res = 0;
while(!que.empty()){
int size = que.size();
for(int i = 0; i < size; ++i){
TreeNode* cur = que.front();
que.pop();
if(i == 0) res = cur->val;
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
}
return res;
}
};
112. 路径总和
/**
* 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:
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == nullptr) return false;
return findpath(root,targetSum-root->val);
}
int findpath(TreeNode* cur, int targetSum){
//cout<<targetSum<<endl;
if(cur->left==nullptr && cur->right == nullptr){
if(targetSum == 0) return 1;
else return 0;
}
if(cur->left) {
int leftnum = findpath(cur->left,targetSum - cur->left->val);
if(leftnum == 1) return 1;
}
if(cur->right){
int rightnum = findpath(cur->right, targetSum - cur->right->val);
if(rightnum == 1) return 1;
}
return 0;
}
};
113. 路径总和ii
很简单
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
if(root == nullptr) return{};
vector<int> vec;
vector<vector<int>> res;
vec.push_back(root->val);
findpath(root,vec,res,targetSum);
return res;
}
void findpath(TreeNode*cur,vector<int>& vec,vector<vector<int>>& res,int targetSum){
if(cur->left == nullptr && cur->right == nullptr){
int sum = 0;
for(int a : vec){
sum += a;
//cout<<a<<endl;
}
if(sum == targetSum) res.push_back(vec);
return;
}
if(cur->left){
vec.push_back(cur->left->val);
findpath(cur->left, vec, res, targetSum);
vec.pop_back();
}
if(cur->right){
vec.push_back(cur->right->val);
findpath(cur->right,vec,res,targetSum);
vec.pop_back();
}
}
};
中序数组大小一定是和后序数组的大小相同的(这是必然)。
中序数组我们都切成了左中序数组和右中序数组了,那么后序数组就可以按照左中序数组的大小来切割,切成左后序数组和右后序数组。