665. Non-decreasing Array

Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.递增

思路:贪心思想,找异常值,存在两个以上则返回false。如果当前的值比前一的值小,并且也比前两的值小,此时只需更改当前值,而不更改前两个值。

更改规则是用前一的值代替当前值。

两种情况

例如: 2   2   1  -》  2  2  2

0   2   1  -》  0  1  1

bool checkPossibility(vector<int>& nums) {
int cnt = ; //如果存在两个以上的异常值则直接返回false
for(int i = ; i < nums.size() && cnt<= ; i++){
if(nums[i-] > nums[i]){ //存在异常值
cnt++;
if(i-< || nums[i-] <= nums[i])nums[i-] = nums[i]; //i-2处理第一个边界值,这种||技巧经常用到
else nums[i] = nums[i-]; //have to modify nums[i]
}
}
return cnt<=;
}

669. Trim a Binary Search Tree

Input:
3
/ \
0 4
\
2
/
1 L = 1
R = 3 Output:
3
/
2
/
1
The code works as recursion.

If the root value in the range [L, R]
we need return the root, but trim its left and right subtree;
else if the root value < L
because of binary search tree property, the root and the left subtree are not in range;
we need return trimmed right subtree.
else
similarly we need return trimmed left subtree. Without freeing memory class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if (root == NULL) return NULL;
if (root->val < L) return trimBST(root->right, L, R);
if (root->val > R) return trimBST(root->left, L, R);
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
}
};

总结:树的遍历bfs,一般结构:

当前root

////////////////////////////

中间逻辑,比如深一层的遍历

///////////////////////////

对当前root进行操作,例如左右边子树的赋值操作

最新文章

  1. JSON: Property &#39;xxx&#39; has no getter method的解决办法
  2. 转--Invalidate和postInvalidate的更新view区别
  3. CSS and JavaScript Bundling and Minification in ASP.NET 4.5
  4. bind()
  5. 小议window.event || ev
  6. Swift中出现“no such module cocoa”的错误
  7. ASP.NET获取IP的6种方法(转载于LanceZhang&#39;s Tech Blog)
  8. C# CreateParams的使用(解决闪屏问题)
  9. Linux下GitLab服务器搭建
  10. java 诊断工具——Arthas
  11. 使用FileZilla从Linux系统下载文件
  12. 使用git将项目上传到github
  13. C++中多维数组传递参数
  14. 新装的arcgis10.5特别卡
  15. 如何将指定文件或文件夹直接提交到svn指定目录
  16. USB2.0学习笔记连载(十四):USB驱动安装及固件程序的编写
  17. 库、教程、论文实现,这是一份超全的PyTorch资源列表(Github 2.2K星)
  18. mybatis匹配字符串的坑
  19. PL/SQL Developer 和 Instant Client客户端安装配置
  20. OO学习体会与阶段总结(设计与实现)

热门文章

  1. idea设置编码格式utf-8
  2. JS流程控制语句 来来回回(Do...while循环) 先执行后判断 do while结构的基本原理和while结构是基本相同的,但是它保证循环体至少被执行一次。
  3. 宽域POST提交数据
  4. layui相关用法总结
  5. slam课程
  6. 新书《iOS应用逆向工程:分析与实战》
  7. 线段树分治初步学习&amp;洛谷P5227[AHOI2013]连通图
  8. [原创]Java调用PageOffice给Word中的Table赋值
  9. 2019-10-31-C#-dotnet-获取整个局域网的-ip-地址
  10. Nginx简介与基础配置