```go
//将二叉树转换成有序双向链表
func _ToSortLinkedList(cur *BinaryNode) {
var tmp = cur.Parant
if cur.Right != nil {
_ToSortLinkedList(cur.Right)
} else {
if tmp.Parant.Right == tmp && tmp.Parant != nil {
if tmp.Left == cur && tmp.Left != nil {
tmp.Parant.Right = cur
cur.Left = tmp.Parant //执行到这里的时候,对tmp.Parent 的影响影响到了递归外。
cur.Right = tmp
}
}
}
if cur.Left != nil {
_ToSortLinkedList(cur.Left)
} else {
if tmp.Parant.Left == tmp && tmp.Parant != nil {
if tmp.Right == cur && tmp.Right != nil {
tmp.Parant.Left = cur
cur.Right = tmp.Parant
cur.Left=tmp
}
}
}
}
```
```
package main
import (
"fmt"
)
// Node 一个带双指针的节点
type Node struct {
left, right *Node
data interface{}
}
// *Node.VisitAsBTreeF 以二叉树前序遍历
func (self *Node) VisitAsBTreeF(fn func(*Node)) {
fn(self)
if self.left != nil {
self.left.VisitAsBTreeF(fn)
}
if self.right != nil {
self.right.VisitAsBTreeF(fn)
}
}
// *Node.VisitAsBTreeM 以二叉树中序遍历
func (self *Node) VisitAsBTreeM(fn func(*Node)) {
if self.left != nil {
self.left.VisitAsBTreeM(fn)
}
fn(self)
if self.right != nil {
self.right.VisitAsBTreeM(fn)
}
}
// *Node.PrintAsLL 以链表遍历 首->尾
func (self *Node) PrintAsLL() {
head := self
for head.left != nil {
head = head.left
}
fmt.Println(head.data)
for head.right != nil {
fmt.Println(head.right.data)
head = head.right
}
}
// B2L BinaryTree to LinkedList
// left -> pre
// right -> next
// 中序
func B2L(root *Node) {
tmparr := [](*Node){}
root.VisitAsBTreeM(func(n *Node) {
tmparr = append(tmparr, n)
})
for i, _ := range tmparr {
if i == 0 {
tmparr[i].left = nil
} else {
tmparr[i].left = tmparr[i-1]
}
if i+1 < len(tmparr) {
tmparr[i].right = tmparr[i+1]
} else {
tmparr[i].right = nil
}
}
}
var (
nid int = 0 // 节点ID
)
// MakeFullTree 新建一个满二叉树 前序
func MakeFullTree(level int) *Node {
if level <= 0 {
return nil
}
// make left
node := new(Node)
node.data = nid
nid += 1
node.left = MakeFullTree(level - 1)
node.right = MakeFullTree(level - 1)
return node
}
func main() {
btree := MakeFullTree(3)
// show btree
btree.VisitAsBTreeF(func(node *Node) {
mark := ""
if node.left == nil && node.right == nil {
mark = "我是叶子"
} else if node.left == nil || node.right == nil {
mark = "我是1度节点"
} else {
mark = "我是2度节点"
}
fmt.Println(mark, node)
})
// 转化
B2L(btree)
// 输出
btree.PrintAsLL()
}
```
#3
更多评论
![bt.png](https://static.studygolang.com/180620/66d0f1ab16a9a469b5ab0ec3f0b3e7dd.png)
#1
最后还是决定重新开辟空间……
```go
func (bt *BinaryNode) ToAscLinkedList() (*SortedLinkedList, error) {
var sum int
bt.GetNodesNum(&sum)
var rs = make([]interface{}, sum)
var flag = 0
bt.ToAscArray(&rs, &flag)
head := New(rs[0])
tail := head
var tmp *BinaryNode
for i := 1; i < len(rs); i++ {
tmp = New(rs[i])
tail.Right = tmp
tmp.Left = tail
tail = tmp
}
return &SortedLinkedList{head}, nil
}
```
#2