题目链接https://leetcode-cn.com/problems/increasing-order-search-tree/
解题代码
/**
* 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* increasingBST(TreeNode* root) {
if(root==NULL){
return nullptr;
}
vector<int> nums;
inOrder(root, nums);
int size = nums.size();
TreeNode* root1 = new TreeNode(nums[0]);
TreeNode* ans = root1;
for(int i=1; i<size; i++){
TreeNode* temp = new TreeNode(nums[i]);
root1->right = temp;
root1 = temp;
}
return ans;
}
void inOrder(TreeNode* root, vector<int>& nums){
if(root==NULL){
return;
}
if(root->left!=NULL){
inOrder(root->left, nums);
}
nums.push_back(root->val);
if(root->right!=NULL){
inOrder(root->right, nums);
}
}
};
运行结果