Skip to content

Instantly share code, notes, and snippets.

@yekmer
Last active January 4, 2016 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yekmer/8639214 to your computer and use it in GitHub Desktop.
Save yekmer/8639214 to your computer and use it in GitHub Desktop.
Solution for print all values at a specific depth in BT, you can see sample BT visualisation here http://www.geeksforgeeks.org/sum-numbers-formed-root-leaf-paths/
public class PrintLevel {
static PrintLevel ts = new PrintLevel();
public static void main(String[] args) {
Node l122 = ts.new Node(null, null, 4);
Node l121 = ts.new Node(null, null, 7);
Node r12 = ts.new Node(null, null, 4);
Node l12 = ts.new Node(l122, l121, 5);
Node l11 = ts.new Node(null, null, 2);
Node r1 = ts.new Node(r12, null, 5);
Node l1 = ts.new Node(l12, l11, 3);
Node root = ts.new Node(r1, l1, 6);
printLevel(root, 1);
}
public static void printLevel(Node node, int level) {
dfsLevel(node, level, 1);
}
public static void dfsLevel(Node node, int level, int curLevel) {
if(node == null) return;
if(level == curLevel) {
System.out.print(node.value + " ");
return;
}
curLevel++;
dfsLevel(node.left, level, curLevel);
dfsLevel(node.right, level, curLevel);
}
class Node {
Node right;
Node left;
int value;
public Node(Node right, Node left, int value) {
this.right = right;
this.left = left;
this.value = value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment