package PocketGems;
import java.util.Stack;
/**
* Created by kangyue on 2/18/17.
*/
public class TernaryParser {
public class Node{
char var;
Node left;
Node right;
Node(char var){
this.var = var;
}
public void display(){
System.out.print(var + " ");
if(left == null) System.out.print("#" + " ");
else left.display();
if(right == null) System.out.print("#" + " ");
else right.display();
}
}
public Node parse(String s){
s = s + ":";
Stack<Node> st = new Stack<>();
Node read = null;
Node root = null;
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(c == '?'){
if(st.isEmpty()){
st.push(read);
root = read;
}
else {
if(st.peek().left == null)st.peek().left = read;
else st.peek().right = read;
st.push(read);
}
} else if(c == ':'){
if(st.peek().left == null)st.peek().left = read;
else st.peek().right = read;
while(!st.isEmpty() && st.peek().right != null){
st.pop();
}
} else {
read = new Node(c);
}
}
return root;
}
public static void main(String[] args){
TernaryParser tp = new TernaryParser();
Node root = tp.parse("a?b?c:d?e:f:c");
root.display();
}
}
[pg]ternery parser to tree
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Given a binary treestruct TreeLinkNode {TreeLinkNode *lef...
- Installation failed with message Failed to establish sess...
- 每个女生都有一颗少女心,粉色的床单,漂亮的蝴蝶结,还有各种萌宠布娃娃,只是随着年龄的增长,身份的转变,对生活的热情...