Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class Node {
- public Node left, right;
- public Node parent;
- public String data;
- public Node(String data, Node parent) {
- this.data = data;
- this.parent = parent;
- }
- public Node addLeft(String data) {
- left = new Node(data, this);
- return left;
- }
- public Node addRight(String data) {
- right = new Node(data, this);
- return right;
- }
- }
- public static void main(String[] args) {
- /* 0 1 2 3 */
- Node root = new Node("root", null);
- {
- Node n10 = root.addLeft("1,0");
- {
- Node n20 = n10.addLeft("2,0");
- {
- Node n30 = n20.addLeft("3,0");
- Node n31 = n20.addRight("3,1");
- }
- Node n21 = n10.addRight("2,1");
- {
- Node n32 = n21.addLeft("3,2");
- Node n33 = n21.addRight("3,3");
- }
- }
- Node n11 = root.addRight("1,1");
- {
- Node n22 = n11.addLeft("2,2");
- Node n23 = n11.addRight("2,3");
- }
- }
- /* 11 nodes
- * *
- * / \
- * * *
- * / \ / \
- * /\ /\
- */
- int deep = 0;
- int lastDeep = 0;
- boolean leftRight = false; // false = left, true = right
- boolean upDown = true; // false = up, true = down
- Node current = root;
- do {
- if (upDown == true) {
- System.out.println(current.data);
- } else if (lastDeep == deep) {
- if (leftRight == false) {
- current = current.right;
- System.out.println(current.data);
- deep++;
- upDown = true;
- leftRight = true;
- } else {
- leftRight = (current.parent.right == current);
- current = current.parent;
- lastDeep--;
- deep--;
- upDown = false;
- }
- }
- if (current.left != null && current.right != null) {
- lastDeep = deep;
- if (upDown == true) {
- current = current.left;
- deep++;
- upDown = true;
- leftRight = false;
- }
- } else {
- leftRight = (current.parent.right == current);
- current = current.parent;
- deep--;
- upDown = false;
- }
- } while (leftRight != true || deep != 0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement