本文主要是介绍代码随想录算法训练营第36期DAY25,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
DAY25
669修剪二叉搜索树
- /**
- * 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 {
- public:
- TreeNode* fdr(TreeNode* root,int low,int high)
- {
- if(root==nullptr) return nullptr;
- if(root->val<low){
- TreeNode* right=fdr(root->right,low,high);
- return right;
- }
- if(root->val>high){
- TreeNode* left=fdr(root->left,low,high);
- return left;
- }
- root->left=fdr(root->left,low,high);
- root->right=fdr(root->right,low,high);
- return root;
- }
- TreeNode* trimBST(TreeNode* root, int low, int high) {
- return fdr(root,low,high);
- }
- };
108将有序数组转为二叉搜索树
有序数组构造二叉树:从数组中间位置取值作为节点元素,就是平衡的了。
根据数组构造二叉树,其本质是寻找分割点,然后递归左区间和右区间。
二分法mid=(left+right)/2可能会爆INT,写成mid=left+(right-left)/2【相当于:偶数取左边】;
- /**
- * 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 {
- public:
- TreeNode* getr(vector<int> &nums,int left,int right)
- {
- if(left>right){
- return nullptr;
- }
- int mid=left+(right-left)/2;
- TreeNode* root=new TreeNode(nums[mid]);
- root->left=getr(nums,left,mid-1);
- root->right=getr(nums,mid+1,right);
- return root;
- }
- TreeNode* sortedArrayToBST(vector<int>& nums) {
- return getr(nums,0,nums.size()-1);
- }
- };
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 GS(TreeNode* root)
- {
- if(root==nullptr) return;
- GS(root->right);
- root->val+=pre;
- pre=root->val;
- GS(root->left);
- }
- public:
- TreeNode* convertBST(TreeNode* root) {
- GS(root);
- return root;
- }
- };
这篇关于代码随想录算法训练营第36期DAY25的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!