碎碎念:
昨天emo偷懒了一天,今天继续补上。有时候感觉自己的心就像海滩,潮起潮落,而且每天晚上和早上,都会冲上岸来一波一波自我厌弃怀疑、后悔焦虑的垃圾,我在这堆海洋垃圾里感到窒息。突然发现每过一天,我都会比昨天更emo,压力也更大,想尝试的无论如何都想尝试,那么我只能持续的努力到明年四月。如果我能做到这件事,我就是最棒的isabel了。
669. 修剪二叉搜索树
链接:代码随想录
解:一定要看视频!清晰易懂,但是我自己单独写不出来。
视频链接:你修剪的方式不对,我来给你纠正一下!| LeetCode:669. 修剪二叉搜索树_哔哩哔哩_bilibili
总结:删除时,,每种情况都要分类讨论清楚。
/** * 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* trimBST(TreeNode* root, int low, int high) { if(root==nullptr) { return root; } else { if(root->val<low)//则root的左子树全部小于root->val,一定被修剪掉;右子树中可能还有在区间的值,所以只需要看root的右子树 { return trimBST(root->right,low,high); } else if(root->val>high)//则root的右子树一定全部大于root-val,不在区间内,只需要修剪root的左子树 { return trimBST(root->left,low,high); } else { root->left=trimBST(root->left,low,high); root->right=trimBST(root->right,low,high); return root; } } } };
108.将有序数组转换为二叉搜索树
链接:代码随想录
自己做出来了,提示:前序遍历,二分,类似根据前序中序遍历构造二叉树。
/** * 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* sortedArrayToBST(vector<int>& nums) { TreeNode *root=helper(nums,0,nums.size()-1); return root; } TreeNode* helper(vector<int>& nums,int low,int high) { if(low<=high) { int mid=low+(high-low)/2; TreeNode *temp=new TreeNode(nums[mid]); temp->left=helper(nums,low,mid-1); temp->right=helper(nums,mid+1,high); return temp; } return nullptr; } };
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 { //后序遍历,累加值 public: int sum=0; TreeNode* convertBST(TreeNode* root) { helper(root); return root; } void helper(TreeNode *root) { if(root!=nullptr) { helper(root->right); sum+=root->val; root->val=sum; helper(root->left); } } };