版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shida_csdn/article/details/83119627
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表 4=6=8=10=12=14=16
分析:
1. 遇到树相关的问题,首先应该想到递归,递归地处理左右子树,获得左子树的 tail,右子树的 head,
将 “左子树的 tail = root = 右子树的 head” 连起来就 OK!
综合起来,递归函数应该能够计算出以当前节点为 root 展成 LinkedList 后的 head 和 tail
2. 需要特别注意对指针参数的处理
package main
import "fmt"
type BSTreeNode struct {
Value int
Left *BSTreeNode
Right *BSTreeNode
}
func TreeToLinkedList(root *BSTreeNode) *BSTreeNode {
var head, tail *BSTreeNode
helper(&head, &tail, root)
return head
}
// 注意对指针的操作(取地址符的使用)
func helper(head, tail **BSTreeNode, root *BSTreeNode) {
var lt, rh *BSTreeNode
if root == nil {
*head, *tail = nil, nil
return
}
helper(head, <, root.Left)
helper(&rh, tail, root.Right)
if lt != nil {
lt.Right = root
root.Left = lt
} else {
*head = root
}
if rh != nil {
root.Right = rh
rh.Left = root
} else {
*tail = root
}
}
func RunTest() {
// create a BSTree
left := &BSTreeNode{1, nil, nil}
right := &BSTreeNode{3, nil, nil}
root := &BSTreeNode{2, left, right}
head := TreeToLinkedList(root)
for p := head; p != nil; p = p.Right {
fmt.Printf("%d ", p.Value)
}
}
func main() {
RunTest()
}