Ternary Expression

来源:互联网 发布:6数字域名 编辑:程序博客网 时间:2024/06/07 00:49
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....


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;  }



0 0
原创粉丝点击