Skip to content

Instantly share code, notes, and snippets.

@anil477
Created June 30, 2017 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/5fc313679fe939d268ad23ba8fe48b68 to your computer and use it in GitHub Desktop.
Save anil477/5fc313679fe939d268ad23ba8fe48b68 to your computer and use it in GitHub Desktop.
Depth or Height of a binary tree
import java.util.Stack;
import java.lang.*;
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
class BinaryTree {
Node root;
public void printHeight() {
System.out.println(" Height " + height(root));
}
public int height(Node root){
if(root==null){
return 0;
}
int left = height(root.left);
int right = height(root.right);
return (Math.max(left, right) + 1);
}
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.printHeight();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment