2016-07-08 44 views
0

Ich erstelle eine doppelt verknüpfte Liste aus einem binären Suchbaum mit Rekursion und es funktioniert einwandfrei, wenn die BST bereits belegt ist, d. H.> = 2 Knoten. Allerdings habe ich versucht, es für eine BST auszuführen, die dynamisch gefüllt wird, und es gibt mir einen StackOverFlowError, sobald ich ein Kind in den Stammknoten in der BST einfügen. Hier ist der Code (in Java) IchBinäre Suchbaumstruktur zu doppelt verknüpfter Liste

geschrieben habe
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); 
    } 

Und das die Konsole Antwort:

Binary Tree Test
Converting to a DLL
Data--34--Left is Null----Right is Null---
Binary Tree Test Converting to a DLL Exception in thread "main" java.lang.StackOverflowError
at com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)
at com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)
at com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)
at com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)
at com.techwealth.BSTtoDLL.BinaryTree2DoubleLinkedList(BSTtoDLL.java:32)

Antwort

0

Offensichtlich haben Sie die Abbruchbedingung fehlt (das Basismodell ist, wie Sie für ungültig erklärt, statische Variablen verwenden). Das ist der Grund, warum Sie Stackoverflow-Fehler sehen. Gehen Sie über diesen Link für weitere Informationen bezüglich dieses Fehlers: What is a StackOverflowError?