二叉树转化成双向链表
来源:互联网 发布:java输入字符串语句 编辑:程序博客网 时间:2024/05/02 04:56
将排序二叉树转化成双向链表,应该是一道很常见的面试题目,网上的实现比较多,有用递归也有用中序遍历法的。看到一位外国友人的实现,还是比较清晰的,思路如下:
1,如果左子树不为null,处理左子树
1.a)递归转化左子树为双向链表;
1.b)找出根结点的前驱节点(是左子树的最右的节点)
1.c)将上一步找出的节点和根结点连接起来
2,如果右子树不为null,处理右子树(和上面的很类似)
1.a)递归转化右子树为双向链表;
1.b)找出根结点的后继节点(是右子树的最左的节点)
1.c)将上一步找出的节点和根结点连接起来
3,找到最左边的节点并返回
附上国外友人的链接:http://www.geeksforgeeks.org/in-place-convert-a-given-binary-tree-to-doubly-linked-list/
下面是代码实现:
bintree2listUtil函数返回的node* 是root节点,bintree2list函数返回的是头节点
This is the core function to convert Tree to list. This function follows
steps 1 and 2 of the above algorithm */
node* bintree2listUtil(node* root)
{
// Base case
if
(root == NULL)
return
root;
// Convert the left subtree and link to root
if
(root->left != NULL)
{
// Convert the left subtree
node* left = bintree2listUtil(root->left);
// Find inorder predecessor. After this loop, left
// will point to the inorder predecessor
for
(; left->right!=NULL; left=left->right);
// Make root as next of the predecessor
left->right = root;
// Make predecssor as previous of root
root->left = left;
}
// Convert the right subtree and link to root
if
(root->right!=NULL)
{
// Convert the right subtree
node* right = bintree2listUtil(root->right);
// Find inorder successor. After this loop, right
// will point to the inorder successor
for
(; right->left!=NULL; right = right->left);
// Make root as previous of successor
right->left = root;
// Make successor as next of root
root->right = right;
}
return
root;
}
// The main function that first calls bintree2listUtil(), then follows step 3
// of the above algorithm
node* bintree2list(node *root)
{
// Base case
if
(root == NULL)
return
root;
// Convert to DLL using bintree2listUtil()
root = bintree2listUtil(root);
// bintree2listUtil() returns root node of the converted
// DLL. We need pointer to the leftmost node which is
// head of the constructed DLL, so move to the leftmost node
while
(root->left != NULL)
root = root->left;
return
(root);
0 0
- 二叉树转化成双向链表
- 将排序二叉树转化成双向链表
- 二叉查找树转化成双向链表
- 01二叉查找树转化成双向链表
- 把二叉树转化成双向连表
- 二叉树转换成双向链表
- 二叉树转换成双向链表
- 二叉树转换成双向链表
- 二叉树转换成双向链表
- 二叉树转换成双向链表
- 二叉树转换成双向链表
- 二叉排序树转化成双向链表
- 二叉排序树转化成双向链表
- 【BST】把搜索二叉树转化成双链表
- 非递归实现二叉搜索树转化成双链表
- LintCode378:将二叉查找树转化成双链表
- 把二叉树转换成双向链表
- 二叉搜索树转换成双向链表
- 例题3.5 易爆物 UVa1160
- 【算法杂谈】算法竞赛中数论相关
- 浅谈JAVA的线程安全与性能之间的权衡
- c++Primer,十一,泛型算法
- jQuery笔记
- 二叉树转化成双向链表
- 2015年阿里巴巴校招研发工程师编程题
- java判断生日字符串是否合法
- 数据结构与算法(C语言)<绪论>
- 膆莇莁袅蝿膃芀袈袅节薂袀
- 袂羁节螀肈芀芁薀袀芆芀蚂
- cmd命令看硬盘的分区信息
- 螈膄芆薂羇肃芈蚈蚃羃膁螃
- 肆芆蒂蝿羂莅薄薂袈莅芄螈