|
| 1 | +/* |
| 2 | + * To change this license header, choose License Headers in Project Properties. |
| 3 | + * To change this template file, choose Tools | Templates |
| 4 | + * and open the template in the editor. |
| 5 | + */ |
| 6 | + |
| 7 | +/** |
| 8 | + * |
| 9 | + * @author miqdad |
| 10 | + */ |
| 11 | +class Node { |
| 12 | + |
| 13 | + Node left, right; |
| 14 | + int value; |
| 15 | + |
| 16 | + public Node(int value) { |
| 17 | + this.value = value; |
| 18 | + } |
| 19 | + |
| 20 | + public Node search(int value) { |
| 21 | + if (this.value == value) { |
| 22 | + return this; |
| 23 | + } else if (value < this.value && this.left != null) { |
| 24 | + this.left.search(value); |
| 25 | + } else if (value > this.value && this.right != null) { |
| 26 | + this.right.search(value); |
| 27 | + } |
| 28 | + |
| 29 | + return null; |
| 30 | + } |
| 31 | + |
| 32 | + public void visit() { |
| 33 | + if (this.left != null) { |
| 34 | + this.left.visit(); |
| 35 | + } |
| 36 | + System.out.print(this.value + " "); |
| 37 | + if (this.right != null) { |
| 38 | + this.right.visit(); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + public void addNode(Node node) { |
| 43 | + if (node.value < this.value) { |
| 44 | + if (this.left == null) { |
| 45 | + this.left = node; |
| 46 | + } else { |
| 47 | + this.left.addNode(node); |
| 48 | + } |
| 49 | + } else { |
| 50 | + if (this.right == null) { |
| 51 | + this.right = node; |
| 52 | + } else { |
| 53 | + this.right.addNode(node); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +class Tree { |
| 60 | + |
| 61 | + Node root; |
| 62 | + |
| 63 | + public void addValue(int value) { |
| 64 | + Node node = new Node(value); |
| 65 | + if (this.root == null) { |
| 66 | + this.root = node; |
| 67 | + } else { |
| 68 | + this.root.addNode(node); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + public void binaryTreeSort() { |
| 73 | + this.root.visit(); |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +public class BinaryTree { |
| 78 | + |
| 79 | + public static void main(String[] args) { |
| 80 | + int[] nums = {3, 2, 5, 6, 7, 1, 9, 0}; |
| 81 | + Tree tree = new Tree(); |
| 82 | + for (int n : nums) { |
| 83 | + tree.addValue(n); |
| 84 | + } |
| 85 | + |
| 86 | + tree.binaryTreeSort(); |
| 87 | + System.out.println(""); |
| 88 | + } |
| 89 | +} |
0 commit comments