题目链接
https://leetcode-cn.com/problems/increasing-order-search-tree/

解题思路
1.要让左节点成为根节点,可以利用中序序列的性质(即 左根右)
2.又一个根节点只要求一个子节点,因此我们可以当成链表来进行处理
代码展示
class Solution {
public:
void inorder(TreeNode* root,vector<int>&res){
if(root==nullptr)return;
inorder(root->left,res);
res.push_back(root->val);
inorder(root->right,res);
}
TreeNode* increasingBST(TreeNode* root) {
vector<int>res;
inorder(root,res);
TreeNode* rot=new TreeNode(-1);
TreeNode* temp=rot;
for(int i=0;i<res.size();i++){
temp->right=new TreeNode(res[i]);
temp=temp->right;
}
return rot->right;
}
};
本文介绍了一种将任意二叉搜索树转换为递增顺序搜索树的方法。通过中序遍历获取节点值并重新构建为仅有右子节点的新树实现。此方法保持了元素的递增顺序且不改变原有树结构。
328

被折叠的 条评论
为什么被折叠?



