【问题标题】:How to insert recursively into Binary Tree and also print the elements recursively?如何递归地插入二叉树并递归地打印元素?
【发布时间】:2017-07-13 15:09:09
【问题描述】:

这是我编写的用于创建二叉树并向其中插入元素的 Java 程序。但是,我无法编写递归插入元素的程序,因此不得不分别手动指定左右子节点。

这是我的代码:

public class BinTree {

private Node root;

private class Node {
Node left;
Node right;
int data;

private Node(int data) {
    this.data = data;
    left = null;
    right = null;
}
}
public BinTree() {
root = null;
}
public void preorder(Node temp) {
temp = root;
if(temp != null) {
    System.out.print(temp.data + " ");
    preorder(temp.left);
    preorder(temp.right);
}
}
public void add() {

root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
root.right.left = new Node(60);
}
public static void main(String[] args) {

BinTree bt = new BinTree();
bt.add();
System.out.print(bt.root.data);
System.out.print(" " + bt.root.left.data);
System.out.print(" " + bt.root.right.data);
System.out.print(" " + bt.root.left.left.data);
System.out.print(" " + bt.root.left.right.data);
}
}

另外,我为上述程序编写的前序遍历失败了,我得到了一些无休止的输出。不得不杀了行刑!

因此,如果有人可以为我提供将元素递归地插入二叉树的正确实现,那将是非常有帮助的。

另外,如果可能的话,你能告诉我我在前序遍历中哪里出错了吗?

提前致谢!

【问题讨论】:

  • 不清楚如何递归插入节点;为此目的的函数需要有一个关于如何找到插入位置的标准。
  • 是的,这正是我卡住的地方!上一次插入后找不到下一个插入点的位置!

标签: java data-structures binary-tree


【解决方案1】:

为了部分回答这个问题,preorder 函数包含一个错误,因为它实际上并没有遍历树,而是一遍又一遍地从根开始。改成

public void preorder(Node temp)
{
    if(temp != null)
    {
        System.out.print(temp.data + " ");
        preorder(temp.left);
        preorder(temp.right);
    }
}

并以树的根作为参数调用它。

【讨论】:

  • 非常感谢兄弟! :) 它起作用了....并且由于您的解决方案,我也相应地实现了 find() 函数(类似的逻辑)。但是我仍然坚持递归插入。有什么帮助吗?
猜你喜欢
  • 2016-07-17
  • 1970-01-01
  • 2012-11-16
  • 2019-09-09
  • 1970-01-01
  • 2020-07-24
  • 2014-12-03
相关资源
最近更新 更多