[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 }

 

转载于:https://www.cnblogs.com/lz87/p/7407494.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值