Created
June 30, 2017 09:18
-
-
Save anil477/5fc313679fe939d268ad23ba8fe48b68 to your computer and use it in GitHub Desktop.
Depth or Height of a binary tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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