Skip to content

Instantly share code, notes, and snippets.

@rodolfobandeira
Forked from thmain/DistanceRootToNode.java
Created February 3, 2017 22:54
Show Gist options
  • Save rodolfobandeira/2d52718a2107db000723413299a29b2e to your computer and use it in GitHub Desktop.
Save rodolfobandeira/2d52718a2107db000723413299a29b2e 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