Skip to content

Instantly share code, notes, and snippets.

@fiddlerwoaroof
Created September 22, 2020 22:42
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 fiddlerwoaroof/6d9d7ba0a85814bcfad60e043221231e to your computer and use it in GitHub Desktop.
Save fiddlerwoaroof/6d9d7ba0a85814bcfad60e043221231e to your computer and use it in GitHub Desktop.
Tree Encoding
package co.fwoar.java.tree;
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
static class Tree {
public int val;
public Tree left;
public Tree right;
public Tree(int val, Tree left, Tree right) {
this.val = val;
this.left = left;
this.right = right;
}
}
static Tree Tree(int val, Tree left, Tree right) {
return new Tree(val, left, right);
}
static class Codec {
public String encode(Tree tree) {
if (tree == null) return "n";
var lString = encode(tree.left);
var rString = encode(tree.right);
return String.format("%s %s %d t", lString, rString, tree.val);
}
enum Type {
TREE,
NUM,
NULL
}
static class Wrapper {
Type type;
Tree t;
int i;
public Wrapper(Tree t) {
this.type = Type.TREE;
this.t = t;
}
public Wrapper(int i) {
this.type = Type.NUM;
this.i = i;
}
public Wrapper() {
this.type = Type.NULL;
}
@Override
public String toString() {
return "Wrapper{" +
"type=" + type +
", t=" + t +
", i=" + i +
'}';
}
}
public Tree decode(String[] tokens) {
Deque<Wrapper> stack = new ArrayDeque<>();
for (var token : tokens) {
if (token.equals("n")) {
stack.push(new Wrapper());
} else if (token.equals("t")) {
var v = stack.pop();
var r = stack.pop();
var l = stack.pop();
stack.push(new Wrapper(Tree(v.i, l.t, r.t)));
} else {
var val = Integer.parseInt(token, 10);
stack.push(new Wrapper(val));
}
}
return stack.pop().t;
}
public Tree decode(String string) {
var tokens = string.split(" ");
return decode(tokens);
}
}
public static void main(String[] args) {
var t = Tree(1, Tree(2, null, null), Tree(3, null, Tree(4, null, null)));
var c = new Codec();
System.out.println(c.encode(t));
System.out.println(c.encode(c.decode(c.encode(t))));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment