Write a function to find the depth of a binary tree.
Answer Posted / ravi
Assuming we start with Level 1, (in Java)
{{{
public class BinaryTreeSearch {
/**
* @param args
*/
public static void main(String[] args) {
BinaryTreeSearch test = new BinaryTreeSearch();
Node root = test.new Node(null, null, "Value");
Node last = root;
Node middle = null;
for (int i = 0; i < 10; i++) {
Node temp = test.new Node(null, null, "Value");
last.setLeft(temp);
last = temp;
if (i == 5)
middle = temp;
}
for (int i = 0; i < 20; i++) {
Node temp = test.new Node(null, null, "Value");
middle.setRight(temp);
middle = temp;
}
for (int i = 0; i < 10; i++) {
Node temp = test.new Node(null, null, "Value");
last.setRight(temp);
last = temp;
}
int depth = depth(root, 0);
System.out.println(depth);
}
private static int depth(Node node, int level) {
if (null == node)
return level;
level++;
int leftLevel = depth(node.getLeft(), level);
int rightLevel = depth(node.getRight(), level);
if (leftLevel > rightLevel) {
return leftLevel;
} else {
return rightLevel;
}
}
public class Node {
Node left = null;
Node right = null;
String strValue = null;
public Node(Node left, Node right, String value) {
this.left = left;
this.right = right;
this.strValue = value;
}
public void setLeft(Node left) {
this.left = left;
}
public void setRight(Node right) {
this.right = right;
}
public void setValue(String value) {
this.strValue = value;
}
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
}
}
}}}
Is This Answer Correct ? | 10 Yes | 5 No |
Post New Answer View All Answers
How do you verify if the two sentences/phrases input is an anagram using predefined functions in string.h and by using arrays?
Sir... please give some important coding questions asked by product companies..
Write a routine to implement the polymarker function
why nlogn is the lower limit of any sort algorithm?
Can you send Code for Run Length Encoding Of BMP Image in C Language in linux(i.e Compression and Decompression) ?
How to palindrom string in c language?
What is the match merge ? compare data step match merge with proc sql merge - how many types are there ? data step vs proc sql
can you use proc sql to manpulate a data set or would u prefer to use proc report ? if so why ? make up an example and explain in detail
What is the difference between proc means and proc tabulate ? explain with a simple example when you have to use means or tabulate?
What is full form of PEPSI
What is data _null_? ,Explain with code when u need to use it in data step programming ?
create a C-code that will display the total fare of a passenger of a taxi if the driver press enter,the timer will stop. Every 10 counts is 2 pesos. Initial value is 25.00
could you please send the program code for multiplying sparse matrix in c????
#include
Given a spherical surface, write bump-mapping procedure to generate the bumpy surface of an orange