Height of binary tree in Java | Hindi Coding Community

0

 In last article we saw how can we print the binary tree using post order traversal. In this article we will see how can we print the height of the binary tree. 

So here in the image you can see we have a binary tree. You have to print the height of this binary tree.

In this image we can clearly see that the height of the tree is 3 so our output must be three.

So now we are going to implement a Java code for this problem.

Java Code :


class Node{

int data;
Node left;
Node right;
Node(int data){
this.data=data;
this.left=null;
this.right=null;
}
}

class HindiCodingCommunity{

public static int Height(Node root){
if(root==null){
return 0;
}
else{
return Math.max(Height(root.left),Height(root.right))+1;
}
}

public static void main(String args[])
{
Node root = new Node(1);
root.left = new Node(2);
root.right= new Node(3);

root.left.left= new Node(4);
root.right.left= new Node(5);
root.right.right= new Node(6);

Height(root);
}

}



Time Complexity : O(n)

Auxilary Space : O(h)






Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !