Skip to content

Instantly share code, notes, and snippets.

@thmain
Created February 23, 2016 06:33
Show Gist options
  • Save thmain/b13708497d177b7c1f25 to your computer and use it in GitHub Desktop.
Save thmain/b13708497d177b7c1f25 to your computer and use it in GitHub Desktop.
public class DistanceRootToNode {
public int Pathlength(Node root, int n1) {
if (root != null) {
int x = 0;
if ((root.data == n1) || (x = Pathlength(root.left, n1)) > 0
|| (x = Pathlength(root.right, n1)) > 0) {
return x + 1;
}
return 0;
}
return 0;
}
public static void main(String[] args) throws java.lang.Exception {
Node root = new Node(5);
root.left = new Node(10);
root.right = new Node(15);
root.left.left = new Node(20);
root.left.right = new Node(25);
root.right.left = new Node(30);
root.right.right = new Node(35);
root.left.right.right = new Node(45);
DistanceRootToNode i = new DistanceRootToNode();
System.out.println("Distance from root to 45 is : "
+ (i.Pathlength(root, 45)-1));
}
}
class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment