|
| 1 | +package main |
| 2 | + |
| 3 | +import "fmt" |
| 4 | + |
| 5 | +// definition of a bst node |
| 6 | +type node struct { |
| 7 | + val int |
| 8 | + left *node |
| 9 | + right *node |
| 10 | +} |
| 11 | + |
| 12 | +// definition of a node |
| 13 | +type btree struct { |
| 14 | + root *node |
| 15 | +} |
| 16 | + |
| 17 | +// allocating a new node |
| 18 | +func newNode(val int) *node { |
| 19 | + return &node{val, nil, nil} |
| 20 | +} |
| 21 | + |
| 22 | +// insert nodes into a binary search tree |
| 23 | +func insert(root *node, val int) *node { |
| 24 | + if root == nil { |
| 25 | + return newNode(val) |
| 26 | + } |
| 27 | + if val < root.val { |
| 28 | + root.left = insert(root.left, val) |
| 29 | + } else { |
| 30 | + root.right = insert(root.right, val) |
| 31 | + } |
| 32 | + return root |
| 33 | +} |
| 34 | + |
| 35 | +// inorder traversal algorithm |
| 36 | +// Copies the elements of the bst to the array in sorted order |
| 37 | +func inorderCopy(n *node, array []int, index *int) { |
| 38 | + if n != nil { |
| 39 | + inorderCopy(n.left, array, index) |
| 40 | + array[*index] = n.val |
| 41 | + *index++ |
| 42 | + inorderCopy(n.right, array, index) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +func treesort(array []int, tree *btree) { |
| 47 | + // build the binary search tree |
| 48 | + for _, element := range array { |
| 49 | + tree.root = insert(tree.root, element) |
| 50 | + } |
| 51 | + index := 0 |
| 52 | + // perform inorder traversal to get the elements in sorted order |
| 53 | + inorderCopy(tree.root, array, &index) |
| 54 | +} |
| 55 | + |
| 56 | +// tester |
| 57 | +func main() { |
| 58 | + tree := &btree{nil} |
| 59 | + numbers := []int{5, 4, 3, 2, 1, -1, 0} |
| 60 | + fmt.Println("numbers : ", numbers) |
| 61 | + treesort(numbers, tree) |
| 62 | + fmt.Println("numbers : ", numbers) |
| 63 | +} |
0 commit comments