leetcode 665
阿新 • • 發佈:2018-12-06
trim bfs roo wid 樹的遍歷 遍歷 block als 常用
665. Non-decreasing Array
Input: [4,2,3] Output: True Explanation: You could modify the first4
to1
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 = 0; //如果存在兩個以上的異常值則直接返回false for(int i = 1; i < nums.size() && cnt<=1 ; i++){ if(nums[i-1] > nums[i]){ //存在異常值 cnt++;if(i-2<0 || nums[i-2] <= nums[i])nums[i-1] = nums[i]; //i-2處理第一個邊界值,這種||技巧經常用到 else nums[i] = nums[i-1]; //have to modify nums[i] } } return cnt<=1; }
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進行操作,例如左右邊子樹的賦值操作
leetcode 665