搜索二叉树转链表 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; }
点赞 评论

相关推荐

明天不下雨了:我靠2022了都去字节了还什么读研我教你****:你好,本人985电子科大在读研一,本科西南大学(211)我在字节跳动实习过。对您的岗位很感兴趣,希望获得一次投递机会。
点赞 评论 收藏
分享
01-17 12:35
吉首大学 Java
秋招之BrianGriffin:自己的工作自己做!😡
点赞 评论 收藏
分享
牛客网
牛客企业服务