Fa magasságának számítása

class Node {
	private Node leftChild, rightChild;
	private static int maxHeight = 0;
 
	public Node(Node leftChild, Node rightChild) {
		this.leftChild = leftChild;
		this.rightChild = rightChild;
	}
 
	public Node getLeftChild() {
		return this.leftChild;
	}
 
	public Node getRightChild() {
		return this.rightChild;
	}
 
	private void getMaxHeight(Node node, int iter) {
		if (iter > maxHeight) {
			maxHeight = iter;
		}
		if (node.leftChild != null) {
			getMaxHeight(node.leftChild, iter + 1);
		}
		if (node.rightChild != null) {
			getMaxHeight(node.rightChild, iter + 1);
		}
	}
 
	public int getHeight() {
		maxHeight = 0;
		getMaxHeight(this, 0);
		return maxHeight;
	}
 
	public static void main(String[] args) {
		Node leaf1 = new Node(null, null);
		Node leaf2 = new Node(null, null);
		Node node = new Node(leaf1, null);
		Node root = new Node(node, leaf2);
 
		System.out.println(root.getHeight());
	}
}

Egy másik megoldás:

class Node {
	private Node leftChild, rightChild;
 
	public Node(Node leftChild, Node rightChild) {
		this.leftChild = leftChild;
		this.rightChild = rightChild;
	}
 
	public Node getLeftChild() {
		return this.leftChild;
	}
 
	public Node getRightChild() {
		return this.rightChild;
	}
 
	private int getMaxHeight(Node node, int iter) {
		int left = iter, right = iter;
		if (node.leftChild != null) {
			left = getMaxHeight(node.leftChild, iter + 1);
		}
		if (node.rightChild != null) {
			right = getMaxHeight(node.rightChild, iter + 1);
		}
		return left > right ? left : right; 
	}
 
	public int getHeight() {
		return getMaxHeight(this, 0);
	}
 
	public static void main(String[] args) {
		Node leaf1 = new Node(null, null);
		Node leaf2 = new Node(null, null);
 
		Node node = new Node(leaf1, null);
		Node node2 = new Node(node, null);
		Node root = new Node(node2, null);
 
		System.out.println(root.getHeight());
	}
 
}