二叉树递归的时候,指针被改了造成了无限循环,怎么规避呀

fwhez · · 1072 次点击
最后还是决定重新开辟空间…… ```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
更多评论
![bt.png](https://static.studygolang.com/180620/66d0f1ab16a9a469b5ab0ec3f0b3e7dd.png)
#1
``` 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