Hi I am trying to find the depth of the binary tree. I was trying a different method than the conventional way to do it. My logic is trying to find max of the levels while doing a depth traversal. Following is the code. This approach is not working as the max value is always zero once it reaches the else part. I am not understanding why.
public class BinaryTree {
public static void main(String args[])
{
Node root = new Node(1);
Node two = new Node(2);
Node three = new Node(3);
Node four = new Node(4);
Node five = new Node(5);
Node six = new Node(6);
Node seven = new Node(7);
Node eight = new Node(8);
root.left = two;
root.right = three;
two.left = four;
two.right = five;
three.left = six;
three.right = seven;
five.left = eight;
findDepth(root,0,0);
}
public static void findDepth(Node root,int level, int max)
{
if(root==null)
return ;
else{
if(root.left==null && root.right==null)
{
if(max<level)
{
max=level;
}
level=level-1;
}
findDepth(root.left,level+1,max);
findDepth(root.right,level+1,max);
}
}
}
// The Node class
public class Node {
int data;
Node left;
Node right;
public Node(int i) {
this.data = i;
}
}
I did this and it worked perfectly
public static int findDepth(Node root,int level, int max1, String str)
{
if(root==null)
return 0;
if(max<level)
{
max=level;
}
findDepth(root.left,level+1,max,"left");
findDepth(root.right,level+1,max,"right");
return max;
}
Here max is static member of the class. But i want to point out to another article in stack overflow where they said the value will propagate down to the next recursive call.
Print all paths from root to leaf in a Binary tree
Here the old value of list is getting propagated to all recursive calls