Write a java code to find the height of a binary tree
To find the height of a binary tree in Java, you can use the following recursive approach:
- If the tree is empty (i.e., the root node is null), return 0.
- Otherwise, the height of the tree is equal to the maximum of the heights of the left and right subtrees, plus 1 (to account for the root node).
- To find the height of a subtree, you can recursively call the same method with the root node of the subtree as the argument.
Here is an example of how you might implement this in Java:
class Node {
int data;
Node left;
Node right;
public Node(int data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
}
}
class BinaryTree {
private Node root;
public BinaryTree(Node root) {
this.root = root;
}
public int getHeight() {
return getHeight(root);
}
private int getHeight(Node node) {
if (node == null) {
return 0;
}
int leftHeight = getHeight(node.left);
int rightHeight = getHeight(node.right);
return Math.max(leftHeight, rightHeight) + 1;
}
}
You can then use the getHeight method to find the height of a binary tree as follows:
// Create a binary tree with three levels
Node leaf1 = new Node(1, null, null);
Node leaf2 = new Node(2, null, null);
Node leaf3 = new Node(3, null, null);
Node leaf4 = new Node(4, null, null);
Node leaf5 = new Node(5, null, null);
Node leaf6 = new Node(6, null, null);
Node node1 = new Node(7, leaf1, leaf2);
Node node2 = new Node(8, leaf3, leaf4);
Node node3 = new Node(9, leaf5, leaf6);
Node root = new Node(10, node1, node2);
BinaryTree tree = new BinaryTree(root);
// Print the height of the tree
System.out.println(tree.getHeight()); // Outputs 3
0 Comments
if you are not getting it then ask i am glad to help