【问题标题】:Binary Search Tree Question on Recursive Storage递归存储的二叉搜索树问题
【发布时间】:2018-12-08 14:00:19
【问题描述】:

由于它是一种递归方法,我无法弄清楚如何使用这些 stg 参数来存储树元素数据。 我想将 stg 保留在那里,以便我可以学习如何以递归方法存储该字符串数据。我该怎么做?(基本上我想摆脱 temp1)

编辑:我试过 stg += root.getElement() + " ";返回stg;它没有工作

System.out.println("inOrder 遍历树:" + inOrder(root, ""));

静态字符串 temp1 = "";

public static String inOrder(BinaryTreeNode<String> root, String stg) {
    if (root != null) {

        // recur to left side
        inOrder(root.getLeft(), stg);

        // print the tree element
        temp1 += root.getElement() + " ";

        // recur to right side
        inOrder(root.getRight(), stg);

    }
    stg = temp1;

    return temp1;
} // inOrder

输出示例“按顺序遍历树:1 2 3 X Y Z x y z”

【问题讨论】:

    标签: java recursion binary-search-tree


    【解决方案1】:

    您不需要stg 参数。您只需要连接左侧,然后是当前元素,然后是右侧:

    public static String inOrder(BinaryTreeNode<String> root) {
        if (root == null) {
            return "";
        }
    
        return inOrder(root.getLeft()) + root.getElement() + inOrder(root.getRight());
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-04
      • 1970-01-01
      • 2014-01-02
      • 2014-10-11
      • 2021-07-03
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多