题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向.
核心代码:
<pre><code>`
var leftHead:TreeNode?
var rightHead:TreeNode?
func convertTwoWayList(rootNode:TreeNode?) -> TreeNode? {
convertSubList(rootNode: rootNode)
return leftHead
}
func convertSubList(rootNode:TreeNode?) {
if rootNode == nil {
return
}
convertSubList(rootNode: rootNode?.leftChild)
if rightHead == nil {
leftHead = rootNode
rightHead = rootNode
} else {
// 右节点和根节点双向指针 注意更新右节点
rightHead?.rightChild = rootNode
rootNode?.leftChild = rightHead
rightHead = rootNode
}
convertSubList(rootNode: rootNode?.rightChild)
}`</code></pre>
测试代码:
<pre><code>`
var util:TreeUtil = TreeUtil()
var rootData:[String] = ["10","6","4","#","#","8","#","#","14","12","#","#","16","#","#"]
var preRootNode:TreeNode?
util.createTreeByPreOrderData(root: &preRootNode, listData: rootData)
var searchTree:BinarySearchTree = BinarySearchTree()
var sortHeadNode:TreeNode? = searchTree.convertTwoWayList(rootNode: preRootNode)
while sortHeadNode != nil {
print("节点值:(sortHeadNode!.data!)")
sortHeadNode = sortHeadNode?.rightChild
}`</code></pre>