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) {
int n = nums.size();
if (n == 0) return nullptr;
int half = n / 2;
TreeNode* root = new TreeNode(nums[half]);
vector<int> leftnums(nums.begin(), nums.begin() + half);
vector<int> rightnums(nums.begin() + half + 1, nums.end());
root -> left = sortedArrayToBST(leftnums);
root -> right = sortedArrayToBST(rightnums);
return root;
}
};
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 count = 0;
TreeNode* convertBST(TreeNode* root) {
if (root == nullptr) return nullptr;
convertBST(root -> right);
root -> val = root -> val + count;
count = root -> val;
convertBST(root -> left);
return root;
}
};