-
669. 修剪二叉搜索树
-
class Solution { public: TreeNode* trimBST(TreeNode* root, int low, int high) { if (root == NULL) return NULL; if (root->val < low) return trimBST(root->right, low, high); if (root->val > high) return trimBST(root->left, low, high); root->left = trimBST(root->left, low, high); root->right = trimBST(root->right, low, high); return root; } };
-
108.将有序数组转换为二叉搜索树
-
class Solution { public: TreeNode* solve(vector<int>& nums, int l, int r) { if(l>r) return NULL; TreeNode* node=new TreeNode(); if(l==r){ node->val=nums[l]; return node; } if(l<r){ node->val=nums[(l+r)/2]; node->left=solve(nums,l,(l+r)/2-1); node->right=solve(nums,(l+r)/2+1,r); } return node; } TreeNode* sortedArrayToBST(vector<int>& nums) { TreeNode* ret = solve(nums, 0, nums.size()-1); return ret; } };
-
538.把二叉搜索树转换为累加树
-
class Solution { public: TreeNode* pre = new TreeNode(); void solve(TreeNode* node) { if (node == NULL) return; solve(node->right); node->val+=pre->val; pre=node; solve(node->left); return ; } TreeNode* convertBST(TreeNode* root) { solve(root); return root; } };