Depth of a binary tree is defined as the maximum length of all paths.
If a binary tree has only one node, its depth is 1. Following sample binary tree can be used as a test input.
There is a detailed and helpful description also at this link.
package interviewquestions; class Node<T> { private T data; private Node<T> left; private Node<T> right; Node( T pData, Node<T> pLeft, Node<T> pRight ) { data = pData; left = pLeft; right = pRight; } public void setLeftChild( Node<T> pLeft ) { left = pLeft; } public void setRightChild( Node<T> pRight ) { right = pRight; } public Node<T> getLeftChild() { return left; } public Node<T> getRightChild() { return right; } public T getData() { return data; } } class BinaryTree<T> { Node<T> root; public BinaryTree(){ root = null; } public void setRootNode( Node<T> pRoot ) { root = pRoot; } public int depth() { return depth(root); } private int depth(Node<T> pNode) { if (pNode == null) return 0; int left = depth(pNode.getLeftChild()); int right = depth(pNode.getRightChild()); int result = (left>right) ? (left+1) : (right+1); return result; } } public class BinaryTreeOperations { public static void main(String[] args) { Node<Integer> node1 = new Node<Integer>( 1, null, null ); Node<Integer> node2 = new Node<Integer>( 2, null, null ); Node<Integer> node3 = new Node<Integer>( 3, null, null ); Node<Integer> node4 = new Node<Integer>( 4, null, null ); Node<Integer> node5 = new Node<Integer>( 5, null, null ); Node<Integer> node6 = new Node<Integer>( 6, null, null ); node1.setLeftChild(node2); node1.setRightChild(node3); node2.setLeftChild(node4); node2.setRightChild(node5); node3.setRightChild(node6); BinaryTree<Integer> binaryTree = new BinaryTree<Integer>(); binaryTree.setRootNode(node1); System.out.println("Depth of Binary Tree = "+binaryTree.depth()); } }
Create a BinaryTreeOperations.java file in your workspace.
When the main method inside the BinaryTreeOperations class executed it is going to print :
Depth of Binary Tree = 3
No comments:
Post a Comment