今日刷题3道:669. 修剪二叉搜索树,108.将有序数组转换为二叉搜索树,538.把二叉搜索树转换为累加树。
● 669. 修剪二叉搜索树
题目链接/文章讲解: https://programmercarl.com/0669.%E4%BF%AE%E5%89%AA%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91.html
视频讲解: https://www.bilibili.com/video/BV17P41177ud
class Solution { public: TreeNode* trimBST(TreeNode* root, int low, int high) { if(root==nullptr) return nullptr; if(root->val < low){ TreeNode* right = trimBST(root->right,low,high); return right; } if(root->val > high){ TreeNode* left = trimBST(root->left,low,high); return left; } root->left =trimBST(root->left,low,high); root->right=trimBST(root->right,low,high); return root; } };● 108.将有序数组转换为二叉搜索树
视频讲解:https://www.bilibili.com/video/BV1uR4y1X7qL
class Solution { private: TreeNode* traversal(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 = traversal(nums,left,mid-1); root->right = traversal(nums,mid+1,right); return root; } public: TreeNode* sortedArrayToBST(vector<int>& nums) { TreeNode* root = traversal(nums,0,nums.size()-1); return root; } };● 538.把二叉搜索树转换为累加树
视频讲解:https://www.bilibili.com/video/BV1d44y1f7wP
class Solution { private: int pre=0; void traversal(TreeNode* cur){ if(cur==NULL) return; traversal(cur->right); cur->val+=pre; pre = cur->val; traversal(cur->left); } public: TreeNode* convertBST(TreeNode* root) { pre=0; traversal(root); return root; } }; 标签:right,TreeNode,23,训练营,随想录,E6%,return,root,left From: https://www.cnblogs.com/zzw0612/p/17061118.html