Created
March 5, 2014 07:28
-
-
Save orhanobut/9362716 to your computer and use it in GitHub Desktop.
find the node in k distance in a given tree list, solution 2 : reverse back complexity = o (n)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HelloWorld { | |
public static void main(String[] args) { | |
Node r = new Node(0); | |
r.left = new Node(1); | |
r.right = new Node(2); | |
r.left.left = new Node(3); | |
r.left.right = new Node(4); | |
r.left.left.left = new Node(5); | |
r.right.right = new Node(6); | |
r.right.left = new Node(7); | |
r.right.left.right = new Node(8); | |
find(r, 2); | |
} | |
public static class Node { | |
Node parent; | |
Node left; | |
Node right; | |
int value; | |
public Node(int value) { | |
this.value = value; | |
} | |
} | |
public static void find(Node n, int k) { | |
if (n.left == null && n.right == null) { | |
int x = 0; | |
Node t = n; | |
while (x < k){ | |
t = t.parent; | |
x++; | |
if (t != null && x == k){ | |
System.out.println("leaf : " + n.value + " node in " + k + " distance : " + t.value); | |
} | |
} | |
} | |
if (n.left != null) { | |
n.left.parent = n; | |
find(n.left, k); | |
} | |
if (n.right != null) { | |
n.right.parent = n; | |
find(n.right, k); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment