【面试题27】二叉搜索树与双向链表

【题目描述】

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。

要求不能创建任何新的结点,只能调整树种结点指针的指向。

【解决方案】

我的代码实现,仅供参考:

 1         public static BinaryTreeNode Convert(BinaryTreeNode root)
 2         {
 3             BinaryTreeNode lastOfList = null;
 4             ConvertNode(root,ref lastOfList);
 5 
 6             BinaryTreeNode headOfList = lastOfList;
 7             while (headOfList != null && headOfList.Left != null)
 8                 headOfList = headOfList.Left;
 9 
10             return headOfList;
11         }
12 
13         public static void ConvertNode(BinaryTreeNode node, ref BinaryTreeNode lastOfList)
14         {
15             if (node == null)
16                 return;
17 
18             BinaryTreeNode current = node;
19 
20             if (current.Left != null)
21                 ConvertNode(current.Left, ref lastOfList);
22 
23             current.Left = lastOfList;
24 
25             if (lastOfList != null)
26                 lastOfList.Right = current;
27 
28             lastOfList = current;
29 
30             if (current.Right != null)
31                 ConvertNode(current.Right, ref lastOfList);
32         }
原文地址:https://www.cnblogs.com/HuoAA/p/4807414.html