104. Maximum Depth of Binary Tree
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr) return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
int current_depth = max(left,right)+1;
return current_depth;
}
};
105. Construct Binary Tree from Preorder and Inorder Traversal
二叉树构造
参考集引用于labuladong算法
二叉树的构造问题一般都是使用「分解问题」的思路:构造整棵树 = 根节点 + 构造左子树 + 构造右子树。
前序遍历第一个位置存 root。左子树和右子树分开的,每个子树都是一次前序遍历(root规则适用)root - 左 - 右
中序遍历通过root划分左右子树,左 - root - 右。可以通过中序判断前序左 - 右的那个划分点。
class Solution {
public:
TreeNode* build(vector<int> & preorder, int prestart, int preend,vector<int> &inorder,int instart,int inend){
if(prestart < 0 || preend >= preorder.size()||instart < 0 || inend >= inorder.size()) return nullptr;
if(prestart > preend || instart > inend) return nullptr;
TreeNode* root = new TreeNode(preorder[prestart]);
if(prestart == preend && instart == inend) return root;
int in_spl = distance(inorder.begin(),find(inorder.begin(),inorder.end(),preorder[prestart]));
int pre_spl=preend+1;
for(int i = prestart; i<=preend;i++){ //左闭右闭
if(distance(inorder.begin(),find(inorder.begin(),inorder.end(),preorder[i]))>in_spl){
pre_spl = i;
break;
}
}
TreeNode* Left = build(preorder,prestart+1,pre_spl-1,inorder,instart,in_spl-1);
TreeNode* Right = build(preorder,pre_spl,preend,inorder,in_spl+1,inend);
if(Left!=nullptr) root->left = Left;
if(Right!=nullptr) root->right = Right;
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return build(preorder, 0, preorder.size() - 1,inorder, 0, inorder.size() - 1);
}
};
好歹是做出来了!我只差一点runtime
算法超时在于find了很多次,使用map直接记录index。下次刷题再改吧
108. Convert Sorted Array to Binary Search Tree
区间以后一律采用左闭右开取中值
class Solution {
public:
TreeNode* build(vector<int>& nums, int left, int right){
if(left == right){
TreeNode* root = new TreeNode(nums[left]);
return root;
}
if(left>right) return nullptr;
int spl = (left+right)/2;
TreeNode* root = new TreeNode(nums[spl]);
TreeNode* Left = build(nums,left,spl-1);
TreeNode* Right = build(nums,spl+1,right);
if(Left!=nullptr) root->left = Left;
if(Right!=nullptr) root->right = Right;
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.size() == 0) return nullptr;
return build(nums,0,nums.size()-1);
}
};
114. Flatten Binary Tree to Linked List
class Solution {
public:
void flatten(TreeNode* root) {
if(root == nullptr) return;
flatten(root->left);
flatten(root->right);
TreeNode* left = root->left;
TreeNode* right = root->right;
root->left = nullptr;
root->right = left;
TreeNode* p = root;
while(p->right!=nullptr){
p = p->right;
}
p->right = right;
}
};
思路想出来了,算AC吧。
199. Binary Tree Right Side View
没什么新意,层序遍历
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> answers;
vector<vector<int>> allNodes;
queue<TreeNode*> que;
if(root == nullptr) return answers;
que.push(root);
while(!que.empty()){
int size = que.size();
vector<int> level;
for(int i = 0;i<size;i++){
TreeNode* cur = que.front();
que.pop();
level.push_back(cur->val);
if(cur->left!=nullptr) que.push(cur->left);
if(cur->right!=nullptr) que.push(cur->right);
}
allNodes.push_back(level);
}
for(int i = 0;i<allNodes.size();i++){
int len = allNodes[i].size();
answers.push_back(allNodes[i][len-1]);
}
return answers;
}
};
226. Invert Binary Tree
AC
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==nullptr) return nullptr;
TreeNode* leftroot = invertTree(root->left);
TreeNode* rightroot = invertTree(root->right);
root->right = leftroot;
root->left = rightroot;
return root;
}
};
230. Kth Smallest Element in a BST
class Solution {
public:
vector<int> records;
void traverse(TreeNode* root){
if(root == nullptr) return;
traverse(root->left);
records.push_back(root->val);
traverse(root->right);
}
int kthSmallest(TreeNode* root, int k) {
traverse(root);
return records[k-1];
}
};
236. Lowest Common Ancestor of a Binary Tree
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==nullptr) return nullptr;
if(root->val == p->val) return p;
if(root->val == q->val) return q;
TreeNode* left = lowestCommonAncestor(root->left,p,q);
TreeNode* right = lowestCommonAncestor(root->right,p,q);
if((left == p && right == q)||(left == q && right == p)) return root;
if(left != nullptr) return left;
if(right!= nullptr) return right;
return nullptr;
}
};
好题!使用hash,map存的是prefix sum
problems like "Find a number of continuous subarrays/submatrices/tree paths that sum to target".
- Use a variable to track the current prefix sum and a hashmap "prefix sum -> how many times was it seen so far".
- situation 1:
- situation 2
class Solution {
public:
unordered_map<long, int> map;
int count = 0;
void countPathSum(TreeNode* root, int target, long sum){
if(!root)
return;
sum += root->val; //Path sum from root
if(sum == target)
count++;
if(map.find(sum - target) != map.end()) //checking whether any target sum path present in the path from root to the current node
count += map[sum - target];
map[sum]++;
countPathSum(root->left, target, sum);
countPathSum(root->right, target, sum);
map[sum]--; //After visiting the left and right subtree, we have to reduce this path sum count from map since we are leaving this path
}
int pathSum(TreeNode* root, int targetSum) {
countPathSum(root, targetSum, 0);
return count;
}
};
直径不一定经过root。
既然不是root,那就是每个节点都有可能,递归思路,对每个子树求最大直径
class Solution {
public:
int maxDiameter = 0;
int getDepth(TreeNode* root){
if(root == nullptr) return 0;
int leftMax = getDepth(root->left);
int rightMax = getDepth(root->right);
maxDiameter = max(maxDiameter,leftMax+rightMax);
return 1 + max(leftMax,rightMax);
}
int diameterOfBinaryTree(TreeNode* root) {
getDepth(root);
return maxDiameter;
}
};
回溯开始
遍历多叉树,收集合法答案
问题类型: 子集求和,排列组合等
三要素:
1. 路径 = 已经做出的选择
2. 选择列表 = 当前可做选择
3. 结束条件 = 到达底层
“backtrack 函数就是一个在回溯树上游走的指针“
多叉树的中序遍历框架
有一个全局容器存结果,一个全局变量存上一个根节点值
传参:选择list,start index
常见的base case 比如超过叶子节点高度
共有以下形式:
元素无重不可复选:
【子集】
核心在于只能使用集合位置后面的元素来去重
【组合】
组合是子集的一部分,控制住大小
【排列】:
和子集不同,可以选取集合位置前后的元素
元素可重不可复选:
【组合】比较同层相同元素的使用情况
【全排列】
和标准全排列的不同在于
1、对 nums
进行了排序。
2、添加了一句额外的剪枝逻辑。=> 重复元素的位置相对固定=>【重复元素(后)】必须在【重复元素(前)】使用
还可以在sort后使用prevNum,这样就可以避免走入相同的树枝
元素无重可复选:
【target sum】
对比不可复选,我们发现,只需要去修改start就行 (i + 1 => i,原地踏步)
减枝策略:超过目标和(当全是非负整数)
【排列】
去除所有剪枝逻辑
17. Letter Combinations of a Phone Number
审题问题,字符串的数字对应的字母相对位置不变(reverse函数的用处)
数学思路:统计‘(’ 和‘)’的数量,对于任意长度(0,len-1),都有左括号数量大于等于右括号的数量。统计方法是在函数穿参的时候传入还能用多少左括号和右括号
class Solution {
public:
vector<string> results;
string s = "";
void traverse(vector<vector<string>> options,int level,int current){
if(current > level) return;
if(current == level){
for(int i = 0;i<options[current-1].size();i++){
s += options[current-1][i];
results.push_back(s);
s.pop_back();
}
}
else{
for(int i = 0;i<options[current-1].size();i++){
s += options[current-1][i];
traverse(options,level, current+1);
s.pop_back();
}
}
}
vector<string> letterCombinations(string digits) {
vector<vector<string>> chars;
chars.push_back({"a","b","c"});
chars.push_back({"d","e","f"});
chars.push_back({"g","h","i"});
chars.push_back({"j","k","l"});
chars.push_back({"m","n","o"});
chars.push_back({"p","q","r","s"});
chars.push_back({"t","u","v"});
chars.push_back({"w","x","y","z"});
if(digits.size() == 0) return results;
vector<vector<string>> options;
int dgt = stoi(digits);
int remainder;
while(dgt!=0){
remainder = dgt%10;
options.push_back(chars[remainder-2]);
dgt = dgt/10;
}
reverse(options.begin(),options.end());
traverse(options,options.size(),1);
return results;
}
};
括号合法性用栈判断
括号生成使用回溯
class Solution {
public:
string cur;
vector<string> results;
void generate(int left, int right, string cur){
if(left>right) return;
if(left < 0 || right < 0) return;
if(left == 0 && right == 0){
results.push_back(cur);
return;
}
cur += '(';
generate(left-1,right,cur);
cur.pop_back();
cur += ')';
generate(left,right-1,cur);
cur.pop_back();
}
vector<string> generateParenthesis(int n) {
if(n ==0) return {};
generate(n,n,cur);
return results;
}
};
可重复选(起始index和i相同,防止选前面的重复)
本题规定unique element的candidate数组,所以不用sort然后使用nums[i-1] == nums[i]去重
class Solution {
public:
vector<vector<int>> results;
vector<int> cur;
vector<bool> used;
void backtrack(vector<int>& candidates, vector<int> cur,int target,int index){
if(index >= candidates.size()) return;
if(target <0) return;
if(target == 0){
results.push_back(cur);
}
for(int i=index;i<candidates.size();i++){
if(i>=1 && !used[i-1] && candidates[i-1]==candidates[i]) continue;
cur.push_back(candidates[i]);
used[i] = true;
backtrack(candidates,cur,target-candidates[i],i);
cur.pop_back();
used[i] = false;
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
if(candidates.size()==0) return {};
sort(candidates.begin(),candidates.end());
used = vector(candidates.size(),false);
backtrack(candidates,cur,target,0);
return results;
}
};
需要用used 防止 【1,1,1】 (因为所有元素之用一次,但是每次都要从头开始选,即i= 0)
class Solution {
public:
vector<vector<int>> results;
vector<int> cur;
vector<bool> used;
void traverse(vector<int>& nums,int level){
if(level > nums.size()) return;
if(level == nums.size()){
results.push_back(cur);
return;
}
for(int i = 0; i<nums.size();i++){
if(!used[i]){
used[i] = true;
cur.push_back(nums[i]);
traverse(nums,level+1);
used[i] = false;
cur.pop_back();
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
if(nums.size() == 0) return results;
used = vector(nums.size(),false);
traverse(nums,0);
return results;
}
};
二分查找
换换脑子
33. Search in Rotated Sorted Array
这道题的重点在于
二分的情况一定是有一边是sorted的,因为懒腰斩断不在左就在右
双指针
很好很好的题!有考到二分思想,和普通的二分查找一点点不同,很好的改编题。
class Solution {
public:
int search(vector<int>& nums, int target) {
int lo = 0;
int hi = nums.size() -1;
while(lo <= hi){
int mid = (lo+hi) >>1;
if(nums[mid] == target) return mid;
if(nums[lo] <= nums[mid]){
//left half is sorted
if(target >= nums[lo] && target <= nums[mid]){
hi = mid -1;
}else{
lo = mid +1;
}
}
else{
if(target >= nums[mid] && target <= nums[hi]){
lo = mid +1;
}else{
hi = mid -1;
}
}
}
return -1;
}
};
34. Find First and Last Position of Element in Sorted Array
还是二分,解决完后左右扩散找边界,注意越界情况和if判断的检验先后。什么时候能bug-free
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> results = {-1,-1};
if(nums.size() == 0) return results;
int lo = 0;
int hi = nums.size()-1;
int left = 0;
int right = 0;
int isfind = false;
while(lo <= hi){
int mid = (lo+hi)>>1;
if(nums[mid] == target){
left = mid;
right = mid;
isfind = true;
break;
}
if(nums[mid]>=target){
hi = mid -1;
}
else{
lo = mid +1;
}
}
if(!isfind) return results;
while(left >= 0 && right <= nums.size()-1 && (nums[left] == target || nums[right] == target)){
if(nums[left]==target)left--;
if(nums[right]==target)right++;
}
if(left < 0||nums[left] != target) left++;
if(right >= nums.size()||nums[right] != target) right--;
return {left,right};
}
};