【问题标题】:Insert in binary tree using recursion使用递归插入二叉树
【发布时间】:2018-09-15 11:46:33
【问题描述】:

我正在尝试实现二叉树而不是二叉搜索树。我花了很多时间使用递归编写插入操作,但没有得到。

它应该是一棵从左到右填充的完整树。

有人可以帮助我吗?最好是在 Java 中。

以下是迭代的方法。(:(这甚至不起作用))

  public static void insertNode(Node root,int x){

        if(root==null) {

            root = new Node(x);
            return;
        }

        Node current;
        Queue<Node> qq = new LinkedList<Node>();

        ((LinkedList<Node>) qq).push(root);

        while(true){
            current=qq.peek();
            if(current.leftchild==null){
                Node child = new Node(x);
                child.parent = current;
                current.leftchild=child;

                return;
            }
            else { ((LinkedList<Node>) qq).push(current.leftchild);}
            if(current.rightChild==null){

                Node child = new Node(x);
                child.parent=current;
                current.rightChild=child;
                return;
            }
            else{
                ((LinkedList<Node>) qq).push(current.rightChild);
            }

            ((LinkedList<Node>) qq).pop();


        }

【问题讨论】:

  • 你好,欢迎来到 StackOverflow,这个问题没有提供足够的信息,总是尝试提供一些与你迄今为止用你的一些代码尝试过的东西以及你卡在哪里的信息。帮助人们帮助你。也可以看看:stackoverflow.com/tour
  • 这是一个基本问题,如何进行插入操作。我相信这个问题很清楚。不是吗?
  • 如我的评论中所述,请分享您到目前为止尝试了什么,什么没有奏效?你总是需要提供一个最简单的例子来说明什么是行不通的。
  • @ZeeshanAdil... 我按照你的建议做了。
  • 递归的意义何在?如果插入二叉树,只需将新节点设为树根

标签: java data-structures binary-tree


【解决方案1】:

您的代码的问题在于,当您实际上想要添加到链接列表时,您正在推入链接列表。 LinkedList.push(element)element 添加到列表的前面,而LinkedList.add(element) 将添加element 到末尾。以下是正确的sn-p:

  public static void insertNode(Node root,int x){
  {
      if(root==null) {
          root = new Node(x);
          return;
      }

      Node current;
      Queue<Node> qq = new LinkedList<Node>();

      ((LinkedList<Node>) qq).push(root);

      while(true){
          current=qq.peek();
          if(current.leftchild==null){
              Node child = new Node(x);
              child.parent = current;
              current.leftchild=child;
              return;
           }
           else {
              ((LinkedList<Node>) qq).add(current.leftchild);}
           if(current.rightChild==null){

               Node child = new Node(x);
               child.parent=current;
               current.rightChild=child;
               return;
            }
            else{
                ((LinkedList<Node>) qq).add(current.rightChild);
            }

            ((LinkedList<Node>) qq).pop();
         }
    } 

【讨论】:

    猜你喜欢
    • 2012-11-16
    • 2020-07-24
    • 2014-12-03
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 2011-12-15
    相关资源
    最近更新 更多