Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Main {
- public static void main(String[] args) {
- BinTree tree = new BinTree(7);
- tree.left = new BinTree(0);
- tree.left.left = new BinTree(-2);
- tree.left.left.right = new BinTree(-1);
- tree.left.right = new BinTree(4);
- tree.right = new BinTree(9);
- tree.right.right = new BinTree(99);
- tree.right.left = new BinTree(8);
- System.out.println("min: " + tree.getMin());
- System.out.println("max: " + tree.getMax());
- System.out.println(tree.isSearchTree());
- }
- }
- class BinTree {
- BinTree left, right;
- private int data;
- private static int min;
- private static int max;
- BinTree(int data) {
- this.data = data;
- }
- int getMin() {
- min = Integer.MAX_VALUE;
- return this.getMinHelper();
- }
- private int getMinHelper() {
- if (this.data < BinTree.min) {
- BinTree.min = this.data;
- }
- if (this.left != null) {
- this.left.getMinHelper();
- }
- if (this.right != null) {
- this.right.getMinHelper();
- }
- return BinTree.min;
- }
- int getMax() {
- max = Integer.MIN_VALUE;
- return this.getMaxHelper();
- }
- private int getMaxHelper() {
- if (this.data > BinTree.max) {
- BinTree.max = this.data;
- }
- if (this.left != null) {
- this.left.getMaxHelper();
- }
- if (this.right != null) {
- this.right.getMaxHelper();
- }
- return BinTree.max;
- }
- boolean isSearchTree() {
- if (this.left == null && this.right == null) {
- return true;
- } else if (this.left == null) {
- if (this.right.getMin() > this.data) {
- return this.right.isSearchTree();
- }
- return false;
- } else if (this.right == null) {
- if (this.left.getMax() < this.data) {
- return this.left.isSearchTree();
- }
- return false;
- } else {
- if (this.left.getMax() < this.data && this.right.getMin() > this.data) {
- return this.left.isSearchTree() && this.right.isSearchTree();
- }
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement