513.找树左下角的值
class Solution {
public:
// 每次depth更新后,记录第一个值。
void travel(TreeNode* root, int depth){
depth++;
if(depth > max_depth){ // 最底层出现,保证只记录最左边的值
max_depth = depth;
result = root->val;
}
if(root->left != nullptr){
travel(root->left, depth);
}
if(root->right != nullptr){
travel(root->right, depth);
}
}
int findBottomLeftValue(TreeNode* root) {
travel(root, 0);
return result;
}
private:
int max_depth = INT_MIN;
int result;
};
112. 路径总和
class Solution {
public:
void travel(TreeNode* root, int targetSum, int sum){
if(root == nullptr){
return ;
}
sum += root->val;
if(root->left == nullptr && root->right == nullptr && sum == targetSum){ // 出现结果
result = true;
}
if(root->left != nullptr){
travel(root->left, targetSum, sum);
}
if(root->right != nullptr){
travel(root->right, targetSum, sum);
}
}
bool hasPathSum(TreeNode* root, int targetSum) {
travel(root, targetSum, 0);
return result;
}
private:
bool result = false;
};
113. 路径总和ii
class Solution {
public:
void travel(TreeNode* root, vector<vector<int>>& result, vector<int> path, int targetSum, int cur_sum){
path.push_back(root->val);
cur_sum += root->val;
if(root->left == nullptr && root->right == nullptr && cur_sum == targetSum){
result.push_back(path);
}
if(root->left != nullptr){
travel(root->left, result, path, targetSum, cur_sum);
}
if(root->right != nullptr){
travel(root->right, result, path, targetSum, cur_sum);
}
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<vector<int>> result;
if(root == nullptr){
return result;
}
vector<int> path;
travel(root, result, path, targetSum, 0);
return result;
}
};
106.从中序与后序遍历序列构造二叉树
106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { // 递归,找出root左右部分
int n = postorder.size();
if(n == 0){
return nullptr;
}
TreeNode* root = new TreeNode(postorder[n - 1]);
if(postorder.size() == 1){
return root;
}
vector<int> inorder_left, inorder_right, postorder_left, postorder_right;
int right_flag = 0;
for(int i = 0; i < n; i++){
if(inorder[i] != postorder[n - 1] && right_flag == 0){
inorder_left.push_back(inorder[i]);
postorder_left.push_back(postorder[i]);
}else if(inorder[i] == postorder[n - 1] && right_flag == 0){
right_flag = 1;
}else if(right_flag == 1){
inorder_right.push_back(inorder[i]);
postorder_right.push_back(postorder[i - 1]);
}
}
root->left = buildTree(inorder_left, postorder_left);
root->right = buildTree(inorder_right, postorder_right);
return root;
}
};