Ternary Expression
a?b:c
a
/ \
b c
a?b?c:d:e
a
/ \
b e
/ \
c d
a?b:c?d:e
a
/ \
b c
/ \
d e
input: String expr
output: Expression
expr is valid
format expr: letter mark letter mark letter....
a?b:c
a
/ \
b c
a?b?c:d:e
a
/ \
b e
/ \
c d
a?b:c?d:e
a
/ \
b c
/ \
d e
input: String expr
output: Expression
expr is valid
format expr: letter mark letter mark letter....
public Node ternary(String str) {
Stack<Node> stack = new Stack<Node>();
Node root = new Node(str.charAt(0));
Node n = root;
for (int i = 1; i < str.length(); i += 2) {
if (str.charAt(i) == '?') {
n.left = new Node(str.charAt(i + 1));
stack.add(n);
n = n.left;
} else if (str.charAt(i) == ':') {
n = stack.pop();
while(n.right != null) {
n = stack.pop();
}
n.right = new Node(str.charAt(i + 1));
stack.add(n);
n = n.right;
}
}
return root;
}