如何使用递归来横向化这个二叉树?

时间:2016-04-07 05:21:30

标签: java recursion tree binary-tree nodes

我很困惑。我理解递归,但这个项目让我迷失了。

基本上,这棵树需要像

这样的东西
(a(b()())(c(d()())()))

和输出

a b 
a c d  

话虽如此,每个节点可以有0个,1个或2个孩子。因此,如果节点包含0个孩子,我知道这意味着它需要递归才能采取行动&返回到树的根并转到树的右侧(因为它首先读取左侧)。 总的来说,我只是很困惑。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;


public class BinaryTreeFinal {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String tree = scan.nextLine();//correct format : (a()())
        String[] t = splitTree(tree);
        System.out.println(Arrays.toString(t));
        //System.out.println(tree2("a", "(a(b()())(c(d()())()))"));
    }

    public static String[] splitTree(String tree)
    {
        //expected format
        //(node tree tree)
        //0 1 2-x x-(length-2) length-1
        if(tree.length() <= 2)//tree not long enough to process
            return new String[]{tree};

        String[] temp = new String[3];
        temp[0] = "" + tree.charAt(1);//grab tree node
        tree = tree.substring(2, tree.length()-1);//remove node and outer paren
        int parenCount = 0;//count of open paren
        int endTreeOne = 0;//end of first tree
        for(int i = 0; i < tree.length(); i++)
        {
            if(tree.charAt(i) == '(')
                parenCount++;
            if(tree.charAt(i) == ')')
                parenCount--;
            if(parenCount == 0)
            {
                endTreeOne = i;
                break;//ends for loop early
            }
        }
        temp[1] = tree.substring(0, endTreeOne+1);//left tree
        temp[2] = tree.substring(endTreeOne+1);//right tree
        return temp;
    }

这是代码混乱的地方:

public static char tree2(String root, String path)
{

    int counter = 0;
    String[] trees = splitTree(path);

    if(trees[1].charAt(counter) == '(' && trees[1].charAt(counter++) == ')')
    {
        counter++;
        //return trees[1].charAt(counter);
        return tree2(String, String);
        //System.out.println(trees[1].charAt(counter));


    }
    else 
        //System.out.println(trees[1].charAt(counter));
        return trees[1].charAt(counter);
    //counter++;


}   

非常感谢,我很抱歉让人感到困惑。我不太清楚如何说出来。

1 个答案:

答案 0 :(得分:0)

我使用Stack s。

撰写的一些内容
Input: `(a(b()())(c(d()())()))`

Output: a b 
        a c d 

Input: `(a(b()())(c(d()())(e)))`

Output: a b 
        a c d 
        a c e

正如您可能理解的那样,我没有对此进行彻底测试。请再运行一些测试,看看它是否按要求运行。

让我用几句话来说明我的思考过程。我看到character前面有一个(。只有在有更多孩子出现时才会打印a或父母部分。所以,我想,每当找到)时,我都会检查我的堆栈,看看顶部的元素是否为(。如果是,那很好。如果没有,我会一直弹出,直到找到匹配的括号。一旦完成,我知道我必须移动到控制台的下一行。然后,我需要跟踪我已经在我的堆栈中有哪些字母表,因为它们可能需要作为新孩子的父母重新打印。所以,我做到了。当遇到一个新的孩子时,父母会被打印出来,一切都显得很黄。如果它不是(测试失败),请告诉我。

Stack<Character> stack = new Stack<Character>();
String st = "(a(b()())(c(d()())(e)))";
String parent = null;
for (int i = 0; i < st.length(); i++) {
    char c = st.charAt(i);

    if (c != ')') {

        // if it is an alphabet
        if (c != '(') {
            // will require printing of parents
            // iff there are more characters to print
            if (parent != null) {
                System.out.print(parent);
                parent = null;
            }
            System.out.print(c + " ");
        }
        stack.push(c);
    } else {
        // is the character on top a matching opening bracket?
        // if it is, then nothing to do, if not 
        char curTop = stack.pop();
        if (curTop != '(')
            while (curTop != '(')
                curTop = stack.pop();
        else
            continue;

        // done working with a character; move to next line
        System.out.println();

        // now, need to reprint the `a` portion 
        // iff more children are present
        Stack<Character> temp = new Stack<Character> ();
        while (!stack.isEmpty())
            temp.push(stack.pop());

        while (!temp.isEmpty()) {
            Character ch = temp.pop();
            if (!(ch == '(' || ch == ')')) {
                // store content
                if (parent == null)
                    parent = "";
                parent += ch + " ";
            }

            stack.push(ch);
        }

    }
}