[pg]ternery parser to tree

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 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)