搜索二叉树转链表
struct Node{
int val;
Node* left;
Node* right;
Node(int a):val(a),left(NULL),right(NULL){}
};
void pre(Node* node,Node*& p) {
if (!node) return;
pre(node->left, p);
node->left = p;
if (p) p->right = node;
p = node;
pre(node->right, p);
}
Node* Convert(Node* pRootOfTree) //原地转链表
{
if (!pRootOfTree)
return pRootOfTree;
Node* t = nullptr;
pre(pRootOfTree, t);
while (pRootOfTree->left)
pRootOfTree = pRootOfTree->left;
return pRootOfTree;
}
void insert(Node* root,int t) { //插入二叉搜索树
if (root->val == t)
return;
if (t < root->val&&root->left==NULL) {
root->left = new Node(t);
return;
}
if (t>root->val&&root->right == NULL) {
root->right = new Node(t);
return;
}
if (t < root->val) {
insert(root->left,t);
return;
}
if (t > root->val) {
insert(root->right, t);
return;
}
return;
}
int main() {
int t;
cin >> t;
Node* root = new Node(t);
while (cin>>t) {
insert(root,t);
char c=getchar();
if (c=='\n') {
break;
}
}
root=Convert(root);
while (root) {
cout << root->val;
root = root->right;
}
system("pause");
return 0;
}