Find Maximum element in a Binary Tree


public int findMax(Node root) {
		int rootValue, left, right;
		int max = Integer.MIN_VALUE;

		if (root != null) {
			rootValue = root.getData();
			left =findMax(root.getLeft());
			right=findMax(root.getRight());
			if (left>right) max=left;
			else max=right;
			if(rootValue>max){
				max=rootValue;
			}
		}
		return max;
	}


Class

class Node {
	int data;
	Node left;
	Node right;

	public int getData() {
		return data;
	}

	public void setData(int data) {
		this.data = data;
	}

	public Node getLeft() {
		return left;
	}

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

	public Node getRight() {
		return right;
	}

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

Leave a Reply

Your email address will not be published. Required fields are marked *