代码随想录算法训练营第十八天 | 513.找树左下角的值
513.找树左下角的值
class Solution {
public:
int maxDepth = INT_MIN;
int result;
int findBottomLeftValue(TreeNode* root) {
int depth = 0;
traversal(root, depth);
return result;
}
void traversal(TreeNode* node, int depth) {
if(node->left == nullptr && node->right == nullptr) {
if(maxDepth < depth) {
maxDepth = depth;
result = node->val;
}
return ;
}
if(node->left) {
depth++;
traversal(node->left, depth);
depth--;
}
if(node->right) {
depth++;
traversal(node->right, depth);
depth--;
}
}
};
112.路径总和
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == nullptr) return false;
int sum = root->val;
return traversal(root, sum, targetSum);
}
bool traversal(TreeNode* node, int sum, int targetSum) {
if(node->left == nullptr && node->right == nullptr) {
if(sum == targetSum) return true;
return false;
}
if(node->left) {
sum += node->left->val;
if(traversal(node->left, sum, targetSum)) return true;
sum -= node->left->val;
}
if(node->right) {
sum += node->right->val;
if(traversal(node->right, sum, targetSum)) return true;
sum -= node->right->val;
}
return false;
}
};
113.路经总和II
题目链接
class Solution {
private:
int total = 0;
vector<vector<int>> ans;
vector<int> path;
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
if(root == nullptr) return {};
path.push_back(root->val);
total += root->val;
traversal(root, targetSum);
return ans;
}
void traversal(TreeNode* node, int targetSum) {
if(node->left == nullptr && node->right == nullptr) {
if(total == targetSum) ans.push_back(path);
return ;
}
if(node->left) {
path.push_back(node->left->val);
total += node->left->val;
traversal(node->left, targetSum);
total -= node->left->val;
path.pop_back();
}
if(node->right) {
path.push_back(node->right->val);
total += node->right->val;
traversal(node->right, targetSum);
total -= node->right->val;
path.pop_back();
}
return ;
}
};
106.从中序与后续遍历序列构造二叉树
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
// 后序或者前序数组为空时,直接返回空
if(postorder.size() == 0) return nullptr;
if(postorder.size() == 1) {
// 构造根节点
TreeNode* root = new TreeNode(postorder[0]);
return root;
}
TreeNode * root = new TreeNode();
root->val = postorder.back();
// 切中序数组
int idx = 0;
for(; idx < inorder.size(); ++idx) {
if(inorder[idx] == root->val)
break;
}
// 左中序
vector<int> left_inorder(inorder.begin(), inorder.begin() + idx);
// 右中序
vector<int> right_inorder(inorder.begin() + idx + 1, inorder.end());
// 切后序数组
// 左后序
vector<int> left_postorder(postorder.begin(), postorder.begin() + left_inorder.size());
// 右后序
vector<int> right_postorder(postorder.begin() + left_inorder.size(), postorder.end() - 1);
// 递归构建左子树
root->left = buildTree(left_inorder, left_postorder);
// 递归构建右子树
root->right = buildTree(right_inorder, right_postorder);
return root;
}
};