二进制搜索树到双向链接列表

时间:2016-07-08 11:09:38

标签: binary-search-tree doubly-linked-list

我正在使用递归从二进制搜索树创建双向链接列表,并且当已经填充BST时它完全正常工作,即> = 2个节点。 但是,我尝试将其运行为动态填充的BST,并且只要将子项插入BST中的根节点,它就会给我一个StackOverFlowError。 这是我写的代码(用Java编写)

public class BSTtoDLL {
/* Binary Search Tree to Doubly Linked List conversion*/

     // head --> Pointer to head node of created doubly linked list
     static BTNode head;

     // Initialize previously visited node as NULL. This is
     // static so that the same value is accessible in all recursive
     // calls
     static BTNode prev = null;

    /* BSTtoDLL Construtor */
    public BSTtoDLL(){
        head = null;
        prev = null;
    }

     // A simple recursive function to convert a given Binary tree 
     // to Doubly Linked List
     // root --> Root of Binary Tree
     void BinaryTree2DoubleLinkedList(BTNode root)
     {
         // Base case
         if (root == null)
             return;

         // Recursively convert left subtree
         if(root.left!=null)
            BinaryTree2DoubleLinkedList(root.left);

         // Now convert this node
         if (prev == null){
             head = root;
         }
         else
         {
             prev.right = root;
             root.left = prev;
         }
         prev = root;

         // Finally convert right subtree
         BinaryTree2DoubleLinkedList(root.right);
     }

控制台响应:

  

二叉树测试
  转换为DLL
  数据 - 34 - 左边是空的 - 对   是Null ---
二进制树测试转换为线程中的DLL异常   “main”java.lang.StackOverflowError
at   com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)
    在   com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)
    在   com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)
    在   com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)
    在   com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)

1 个答案:

答案 0 :(得分:0)

显然,您缺少终止条件(基本情况因使用静态变量而失效)。这就是您看到stackoverflow错误的原因。有关此错误的详细信息,请浏览此链接:What is a StackOverflowError?

相关问题