Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Tree {
- Node root;
- public void add(int value) {
- root = addRecursive(root, value);
- }
- private Node addRecursive(Node current, int value) {
- if (current == null) {
- return new Node(value);
- }
- if (value < current.value) {
- current.left = addRecursive(current.left, value);
- } else if (value > current.value) {
- current.right = addRecursive(current.right, value);
- }
- return current;
- }
- public boolean isEmpty() {
- return root == null;
- }
- public void dfs(Node node) {
- if (node != null) {
- System.out.print(" " + node.value);
- dfs(node.left);
- dfs(node.right);
- }
- }
- public void bfs() {
- if (root == null) {
- return;
- }
- Queue<Node> nodes = new LinkedList<>();
- nodes.add(root);
- while (!nodes.isEmpty()) {
- Node node = nodes.remove();
- System.out.print(" " + node.value);
- if (node.left != null) {
- nodes.add(node.left);
- }
- if (node.right!= null) {
- nodes.add(node.right);
- }
- }
- }
- }
- class Node {
- int value;
- Node left;
- Node right;
- Node(int value) {
- this.value = value;
- right = null;
- left = null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement