[pg]ternery parser to tree
作者:
秋_轩 | 来源:发表于
2017-02-19 12:36 被阅读0次
instant
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
本文链接:https://www.haomeiwen.com/subject/dqhjwttx.html
网友评论