`

Pocket Gems - Ternary Expression to Binary Tree

 
阅读更多

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:

http://stackoverflow.com/questions/28487831/how-to-convert-a-ternary-expression-to-a-binary-tree-structure

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics