把二元查找树转变成排序的双向链表
2017-12-27 16:19
381 查看
把二元查找树转变成排序的双向链表
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16
4=6=8=10=12=14=16
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16
#pragma warning(disable:4996) #include <cstdio> #include <cstring> #define ll long long int struct node { int data; struct node* left = nullptr; struct node* right = nullptr; }; node* root = nullptr; void Insert(node* nd,node* cur) { if(nd->data > cur->data) { if (cur->right == nullptr) cur->right = nd; else Insert(nd, cur->right); } else { if (cur->left == nullptr) cur->left = nd; else Insert(nd, cur->left); } } void BuildTree(int n) { for(int i = 0; i < n; i++) { node* nd = new node; scanf("%d", &nd->data); if (root == nullptr) root = nd; else Insert(nd, root); } } node* GetLeft(node* nd) { if (nd == nullptr) return nullptr; while (nd->left != nullptr) nd = nd->left; return nd; } node * GetRight(node* nd) { if (nd == nullptr) return nullptr; while (nd->right != nullptr) nd = nd->right; return nd; } node* ToDLinkList(node * last,node * cur) { node* left = nullptr, *right = nullptr; if (cur->left != nullptr) left = ToDLinkList(cur, cur->left); if (cur->right != nullptr) right = ToDLinkList(cur, cur->right); if (left != nullptr) left->right = cur; if (right != nullptr) right->left = cur; cur->left = left; cur->right = right; if(last != nullptr) { if (cur->data < last->data) return GetRight(cur); else return GetLeft(cur); } return cur; } int main() { #ifdef local //freopen("data.txt", "r", stdin); #endif int n; scanf("%d", &n); BuildTree(n); root = ToDLinkList(nullptr, root); root = GetLeft(root); while (root != nullptr) { printf("%d ", root->data); root = root->right; } printf("\n"); }
4=6=8=10=12=14=16
相关文章推荐
- 天天算法03——二元查找树转变成排序的双向链表
- [算法] 把二元查找树转变成排序的双向链表
- 二元查找树转变成排序的双向链表
- 中序线索二叉树算法 解决 把二元查找树转变成排序的双向链表
- 数据结构练习(01)把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 程序员面试题精选100题(01)-把二元查找树转变成排序的双向链表[数据结构]
- 每天一算法(把二元查找树转变成排序的双向链表 )
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表[数据结构]
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 第一题 把二元查找树转变成排序的双向链表
- 程序员面试题精选100题(01)-把二元查找树转变成排序的双向链表[数据结构]
- 把二元查找树转变成排序的双向链表
- 程序员面试题精选100题(01)-把二元查找树转变成排序的双向链表
- 把二元查找树转变成排序的双向链表
- 1.二元查找树转变成排序的双向链表