[GeeksForGeeks] Tree Sort

Given an unsorted array of integers, sort this array using tree sort.

 

1. Create a binary search tree by inserting array elements.

2. Perform in order traversal on the bst to get the array elements in sorted order.

 

 1 public class TreeSort {
 2     public TreeNode treeSort(TreeNode root, int[] arr) {
 3         if(arr == null || arr.length == 0) {
 4             return root;
 5         }
 6         for(int i = 0; i < arr.length; i++) {
 7             TreeNode node = new TreeNode(arr[i]);
 8             TreeNode temp = insertToBst(root, node);
 9             if(i == 0) {
10                 root = temp;
11             }
12         }
13         return root;
14     }
15     private TreeNode insertToBst(TreeNode root, TreeNode node) {
16         if(root == null) {
17             return node;
18         }
19         if(node.val < root.val) {
20             root.left = insertToBst(root.left, node);
21         }
22         else {
23             root.right = insertToBst(root.right, node);
24         }
25         return root;
26     }
27     private void inOrder(TreeNode node) {
28         if(node == null) {
29             return;
30         }
31         inOrder(node.left);
32         System.out.println(node.val);
33         inOrder(node.right);
34     }
35     public static void main(String[] args) {
36         int[] arr = {1, 3, 4, 8, 2, 0};
37         TreeSort test = new TreeSort();    
38         test.inOrder(test.treeSort(null, arr));
39     }
40 }

 

posted @ 2017-08-22 01:44  Review->Improve  阅读(228)  评论(0编辑  收藏  举报