【问题标题】:How do I transverse this binary tree using recursion?如何使用递归遍历这棵二叉树?
【发布时间】:2016-07-27 19:29:25
【问题描述】:

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

基本上,这棵树需要类似

(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++;


}   

非常感谢,很抱歉让您感到困惑。我不知道该怎么说。

【问题讨论】:

  • 这里有需要使用二叉树的原因吗?只是好奇。
  • 我的教授在这里需要二叉树。
  • 啊!哈哈,我正在做一个基于Stack 的方法。即将更新:)
  • 我愿意接受任何建议或例子!
  • 好了,伙计。基于Stack 的方法。让我想想基于树的方法。也许,您会根据我的回答找到一些想法。

标签: java recursion tree binary-tree nodes


【解决方案1】:

我用Stacks 写的一些小东西。

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

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    相关资源
    最近更新 更多