题目:输入一棵二叉搜索树,将该二叉树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
解题思路:在二叉树中,每个结点都有两个指向子结点的指针。在双向链表中,每个结点也有两个指针。在搜索二叉树中左子结点的值总是小于父结点的值,右子结点的值总是大于父结点的值。在转换成排序双向链表时,原先指向左子结点的指针调整为链表中指向前一个结点的指针,原先指向右子结点的指针调整为链表中指向后一个结点的指针。
C#实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
public static BinaryTreeNode Convert(BinaryTreeNode pRootOfTree)
{
BinaryTreeNode pLastNodeInList = null ;
ConvertNode(pRootOfTree, ref pLastNodeInList);
// pLastNodeInList指向双向链表的尾结点
// 需要返回头结点
BinaryTreeNode pHeadOfList = pLastNodeInList;
while (pHeadOfList != null && pHeadOfList.left != null )
pHeadOfList = pHeadOfList.left;
return pHeadOfList;
}
private static void ConvertNode(BinaryTreeNode pNode, ref BinaryTreeNode pLastNodeInList)
{
if (pNode == null )
return ;
BinaryTreeNode pCurrent = pNode;
if (pCurrent.left != null )
ConvertNode(pCurrent.left, ref pLastNodeInList);
pCurrent.left = pLastNodeInList;
if (pLastNodeInList != null )
pLastNodeInList.right = pCurrent;
pLastNodeInList = pCurrent;
if (pCurrent.right != null )
ConvertNode(pCurrent.right, ref pLastNodeInList);
}
|
Java实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
public static BinaryTreeNode Convert(BinaryTreeNode pRootOfTree){
BinaryTreeNode pLastNodeInList = null ;
List<BinaryTreeNode> lst = new LinkedList<BinaryTreeNode>();
lst.add(pLastNodeInList);
ConvertNode(pRootOfTree, lst);
// pLastNodeInList指向双向链表的尾结点
// 需要返回头结点
BinaryTreeNode pHeadOfList = lst.get( 0 );
while (pHeadOfList != null && pHeadOfList.left != null )
pHeadOfList = pHeadOfList.left;
return pHeadOfList;
}
private static void ConvertNode(BinaryTreeNode pNode, List<BinaryTreeNode> lst)
{
if (pNode == null )
return ;
BinaryTreeNode pCurrent = pNode;
if (pCurrent.left != null )
ConvertNode(pCurrent.left, lst);
pCurrent.left = lst.get( 0 );
if (lst.get( 0 ) != null )
lst.get( 0 ).right = pCurrent;
lst.set( 0 , pCurrent);
if (pCurrent.right != null )
ConvertNode(pCurrent.right, lst);
}
|
Python实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
@staticmethod def convert(pRootOfTree):
"""
二叉搜索树与双向链表
输入一棵二叉搜索树,将该二叉树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
:param pRootOfTree:
:return:
"""
pLastNodeInList = None
lst = [pLastNodeInList]
BinaryTree._convertNode(pRootOfTree, lst)
# pLastNodeInList指向双向链表的尾结点
# 需要返回头结点
pHeadOfList = lst[ 0 ]
while pHeadOfList ! = None and pHeadOfList.left ! = None :
pHeadOfList = pHeadOfList.left
return pHeadOfList
@ staticmethod
def _convertNode(pNode, lst):
if pNode = = None :
return
pCurrent = pNode
if pCurrent.left ! = None :
BinaryTree._convertNode(pNode.left, lst)
pCurrent.left = lst[ 0 ]
if lst[ 0 ] ! = None :
lst[ 0 ].right = pCurrent
lst[ 0 ] = pCurrent
if pCurrent.right ! = None :
BinaryTree._convertNode(pCurrent.right, lst)
|
本文转自 许大树 51CTO博客,原文链接:http://blog.51cto.com/abelxu/1976690,如需转载请自行联系原作者