二叉查找树@TOC
题目:输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求:不能创建任何新的结点,只调整指针的指向。
10
/
6 14
/ \ /
4 8 12 16
转换成双向链表 4=6=8=10=12=14=16
前提:整数数组中没有重复的数字
原理
1.任意数组,创建二叉查找树
2.中序遍历二叉查找树
3.递归调整节点左右指针
实现
package main
import(
"fmt"
"strconv"
)
// 定义二叉树的节点结构
type BSTreeNode struct {
Value int
Left *BSTreeNode
Right *BSTreeNode
}
// 创建一个二叉树的节点
func create_new_node(data int) *BSTreeNode {
new_node := new(BSTreeNode)
new_node.Value = data
new_node.Left = nil
new_node.Right = nil
return new_node
}
// 创建二叉树,或者向二叉树中插入节点
func buildBinarySearchTree(root **BSTreeNode, data int) {
tmp_node := *root
pre_node := new(BSTreeNode)
pre_node = nil
if *root == nil {
*root = create_new_node(data)
} else {
for tmp_node != nil {
pre_node = tmp_node
if tmp_node.Value > data {// 创建左子树
tmp_node = tmp_node.Left
if tmp_node == nil {
pre_node.Left = create_new_node(data)
}
} else {// 创建右子树
tmp_node = tmp_node.Right
if tmp_node == nil {
pre_node.Right = create_new_node(data)
}
}
}
}
}
// 中序遍历有序二叉树
func SearchBinaryTree(root *BSTreeNode) {
if root == nil {
return
}
SearchBinaryTree(root.Left)
fmt.Printf(strconv.Itoa(root.Value) + " ")
SearchBinaryTree(root.Right)
}
// 创建二叉查找树
func BuildBSTree(data_list []int) **BSTreeNode{
if data_list == nil {
return nil
}
root := new(BSTreeNode)
for i := 0; i < len(data_list); i++ {
buildBinarySearchTree(&root, data_list[i])
}
return &root
}
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(root **BSTreeNode) {
if root == nil {
return
}
head := TreeToLinkedList(*root)
for p := head; p != nil; p = p.Right {
fmt.Printf("%d ", p.Value)
}
}
func main() {
val := []int{100,5,6,1,3,4}
root := BuildBSTree(val)
SearchBinaryTree(*root)
fmt.Println("")
RunTest(root)
fmt.Println("")
}