java开发实现二叉树
java开发实现二叉树
代码如下:
- package com.litao;
- import java.util.Arrays;
- public class Node
- {
- private Node right;
- private Node left;
- private int value;
- public Node(int value)
- {
- this.value = value;
- }
- public void add(int value)
- {
- if (value > this.value)
- {
- if (right != null)
- {
- right.add(value);
- } else
- {
- Node node = new Node(value);
- right = node;
- }
- } else
- {
- if (left != null)
- {
- left.add(value);
- } else
- {
- Node node = new Node(value);
- left = node;
- }
- }
- }
- public boolean find(int value)
- {
- if (value == this.value)
- {
- return true;
- } else if (value > this.value)
- {
- if (right == null)
- {
- return false;
- } else
- {
- return right.find(value);
- }
- } else
- {
- if (left == null)
- {
- return false;
- } else
- {
- return left.find(value);
- }
- }
- }
- public static boolean contains(int[] arr, int value)
- {
- for (int i = 0; i < arr.length; i++)
- {
- if (arr[i] == value)
- {
- return true;
- }
- }
- return false;
- }
- public void diaplay()
- {
- System.out.println(value);
- if (right != null)
- {
- right.diaplay();
- }
- if (left != null)
- {
- left.diaplay();
- }
- }
- public static void main(String[] args)
- {
- int[] values = new int[8];
- for (int i = 0; i < values.length; i++)
- {
- int num = (int) (Math.random() * 15);
- if(!contains(values, num))
- {
- values[i] = num;
- }else
- {
- i–;
- }
- }
- System.out.println(Arrays.toString(values));
- Node node = new Node(values[0]);
- for(int i = 1; i < values.length;i++)
- {
- node.add(values[i]);
- }
- System.out.println(node.find(11));
- node.diaplay();
- }
- }