搜寻与串的二进制树

时间:2018-03-30 20:32:50

标签: java recursion binary-tree

到目前为止,这是我的代码,用于查找char字符表示的所有节点。我已经能够使用辅助方法编写如何获取根节点的“(”和“)”。但是,在尝试将辅助方法集成到treeProcessor中时,我遇到了一个心灵障碍。在treeProcessor方法中,我正在尝试进一步深入研究二叉树,以便最终目标是打印出根节点和子树。

public static ArrayList<String> paths = new ArrayList<>();

    public static void main(String[] args) 
    {

        String tree = "(a(b()())(c()()))";

        //replace this line with a call to the treeProcessor
        System.out.println(Arrays.toString(treeBreakdownHelper(tree)));//a, (b()()), (c()())
        System.out.println();

        System.out.println(paths);//prints every path found
    }

    //recursive method
    public static void treeProcessor(String tree, String path)
    {
        //breakdown tree


        //update path


        //check if current element is leaf/last element
            //if it is, add to ArrayList

        //if not last element, run processor again on subtrees that are not empty
    }
    //valid tree:
    //(a()())
    //(a(b()())(c()()))
    //helper method
    public static String[] treeBreakdownHelper(String tree)
    {
        String[] temp = new String[3];
        //0 = root
        //1 = left tree
        //2 = right tree
        tree = tree.substring(1, tree.length()-1);

        //System.out.println(tree);//test removal of outer parens
        temp[0] = "" + tree.charAt(0);
        tree = tree.substring(1);

        //System.out.println(tree);//test removal of root node
        int openCount = 0;
        int middle = 0;

        for(int i = 0; i < tree.length(); i++)
        {
            //System.out.println(openCount);
            if(tree.charAt(i) == '(')
            {
                openCount++;
            }
            else if(tree.charAt(i) == ')')
            {
                openCount--;
            }
            if(openCount == 0)
            {
                middle = i;
                break;
            }
        }
        //System.out.println(middle);
        //System.out.println(tree.substring(0,middle+1));
        temp[1] = tree.substring(0,middle+1);
        //System.out.println(tree.substring(middle+1));
        temp[2] = tree.substring(middle+1);

        return temp;

    }

}

0 个答案:

没有答案