Solution :

Node.java

package com.adaming;

public class Node {

	int value;
	Node right, left;

	public Node(int value, Node right, Node left) {
		super();
		this.value = value;
		this.right = right;
		this.left = left;
	}
	
	

	public Node(int value, Node right) {
		super();
		this.value = value;
		this.right = right;
	}
	
	



	public Node(Node left , int value) {
		super();
		this.value = value;
		this.left = left;
	}

	
	


	public Node(int value) {
		super();
		this.value = value;
	}



	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
	}

	public Node getRight() {
		return right;
	}

	public void setRight(Node right) {
		this.right = right;
	}

	public Node getLeft() {
		return left;
	}

	public void setLeft(Node left) {
		this.left = left;
	}

	public Node find(int v) {
		if (v == this.value) {
			return this;
		} else if (this.left == null && this.right == null) {
			return null;
		} else if (this.right == null && v > this.value) {
			return null;
		} else if (this.left == null && v < this.value) {
			return null;
		} else if (v < this.value) {
			return this.left.find(v);
		} else {
			return this.right.find(v);
		}

	}



	@Override
	public String toString() {
		return "Node [value=" + value + ", right=" + right + ", left=" + left + "]";
	}
	
	

}

Main.java : Filling the binary tree to test…

package com.adaming;

public class Main {

	public static void main(String[] args) {
		
		Node n1 = new Node(6);
		Node n2 = new Node(2);
		Node n3 = new Node(5, n1, n2);
		
		Node n4 = new Node(8);
		Node n5 = new Node(7, n4, n3);
		
		
		Node n6 = new Node(16);
		Node n7 = new Node(n6, 17);
		
		Node n8 = new Node(13, n7);
		
		Node Arbre = new Node(9, n8, n5);
		
		System.out.println(Arbre.find(7));

		
	}

}

Laisser un commentaire