把二叉搜索树转换为累加树
[题目](538. 把二叉搜索树转换为累加树)
重点
使用中序遍历,但是需要是倒序
代码实现
/**
* 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 {
private:
// 记录前一个节点的数值
int pre = 0;
void traversal(TreeNode* cur) {
// 中右左遍历
if (!cur) {
return;
}
traversal(cur->right);
cur->val += pre;
pre = cur->val;
traversal(cur->left);
}
public:
TreeNode* convertBST(TreeNode* root) {
pre = 0;
traversal(root);
return root;
}
};
组合
[题目](77. 组合)
代码实现
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(int n, int k, int startIndex) {
if (path.size() == k) {
result.push_back(path);
return;
}
for(int i = startIndex; i <= n - (k - path.size()) + 1; i++) {
// 处理节点
path.push_back(i);
backtracking(n, k, i + 1);
// 回溯,撤销处理的节点
path.pop_back();
}
}
public:
vector<vector<int>> combine(int n, int k) {
backtracking(n, k, 1);
return result;
}
};