669. 修剪二叉搜索树

递归左右子树.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     TreeNode* trimBST(TreeNode* root, int low, int high) {
15         if(root == nullptr) return nullptr;
16         if(root->val < low && root->val > high)   return nullptr;
17         if(root->val < low) return trimBST(root->right, low, high);
18         if(root->val > high)    return trimBST(root->left,low,high);
19         root->left = trimBST(root->left, low, high);
20         root->right = trimBST(root->right, low, high);
21         return root;
22     }
23 };

108. 将有序数组转换为二叉搜索树

中间分段,然后递归

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     TreeNode* sortedArrayToBST(vector<int>& nums) {
15         int n = nums.size();
16         if(n == 0)  return nullptr;
17         int mid = n/2;
18         TreeNode* root = new TreeNode(nums[mid]);
19         vector<int> left(nums.begin(),nums.begin()+mid);
20         vector<int> right(nums.begin()+mid+1,nums.end());
21         root->left = sortedArrayToBST(left);
22         root->right = sortedArrayToBST(right);
23         return root;
24     }
25 };

538. 把二叉搜索树转换为累加树

右中左遍历二叉树

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     int sum = 0;
15     TreeNode* convertBST(TreeNode* root) {
16         if(root == nullptr) return nullptr;
17         rdl(root);
18         return root;
19     }
20 private:
21     void rdl(TreeNode* node){
22         if(node == nullptr) return;
23         rdl(node->right);
24         sum += node->val;
25         node->val = sum;
26         rdl(node->left);
27     }
28 };