I came across this problem that has Ternary expression (a?b:c) and needs the ternary expression to be converted into a Binary tree structure.
a?b:c
a
/ \
b c
a?b?c:d:e
a
/ \
b e
/ \
c d
public TreeNode convertToBT (char[] values) { TreeNode root = new TreeNode(values[0]); TreeNode n = root; Stack<TreeNode> a = new Stack<TreeNode>(); for (int i = 1; i < values.length; i += 2) { if (values[i] == '?') { n.left = new TreeNode (values[i + 1]); a.add(n); n = n.left; } else if (values[i] == ':') { n = a.pop(); while (n.right != null) { n = a.pop(); } n.right = new TreeNode (values[i + 1]); a.add(n); n = n.right; } } return root; }
Reference: