繁体   English   中英

Java:二叉树+前序遍历+递归+返回结果列表

[英]Java : binary tree + preorder traversal + recursion + return a result list

小 Java 问题关于二叉树的前序遍历,使用递归,请返回所有元素的结果列表。

查看 web 我们可以看到许多关于使用递归遍历树的结果。 但是,它们都“只打印”节点,不返回任何内容:

https://makeinjava.com/recursive-binary-tree-traversal-algorithm-java-preorder-postorderinorder/

public static void preOrderRecursive(Node root) {
    if (null == root) {
        return;
    }
    System.out.printf("%d ", root.data);
    preOrderRecursive(root.left);
    preOrderRecursive(root.right);
}

这是一个递归 function 但不返回任何东西

另一方面,有许多示例将二叉树作为列表返回,但使用迭代方式:

public List<Integer> preorderIterative(TreeNode root) {
    LinkedList<TreeNode> stack = new LinkedList<>();
    LinkedList<Integer> output = new LinkedList<>();
    if (root == null) {
      return output;
    }

    stack.add(root);
    while (!stack.isEmpty()) {
      TreeNode node = stack.pollLast();
      output.add(node.val);
      if (node.right != null) {
        stack.add(node.right);
      }
      if (node.left != null) {
        stack.add(node.left);
      }
    }
    return output;
  }

这是一个迭代的 function,它确实将结果作为列表返回

我的问题是,我很难构建一个递归 function ,它将结果作为列表返回。

我尝试过的(但没有工作):

 public static List<Integer> preOrderRecursiveWithReturn(TreeNode root) {
        if (null == root) {
            return ???;
        } else {
            return preOrderRecursiveWithReturn(root.left) preOrderRecursiveWithReturn(root.right) ???
        }
    }

但不幸的是,它不起作用。 请问有什么帮助吗?

谢谢

另一种选择是不让递归方法返回列表,而是让递归方法添加到列表字段。

private List<Integer> output;

public static void preOrderRecursive(Node root) {
if (null == root) {
    return;
}
//System.out.printf("%d ", root.data);
list.add(root.data);
preOrderRecursive(root.left);
preOrderRecursive(root.right);

}

创建一个将 output 列表作为额外参数的助手 function:

    // Helper
    private static void preOrderRecursive(Node root, LinkedList<Integer> output) {
        if (null == root) {
            return;
        }
        output.add(root.data);
        preOrderRecursive(root.left, output);
        preOrderRecursive(root.right, output);
    }

    // Actual function that returns the list
    public static LinkedList<Integer> preOrder(Node root) {
        LinkedList<Integer> output = new LinkedList<Integer>();
        preOrderRecursive(root, output);
        return output;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM