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

时间:2016-07-05 15:27:31

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

我正在将二进制搜索树转换为双向链接列表,并使用递归进行转换。但是,递归永远不会结束并给我一个StackOverFlow错误。我无法理解我哪里出错了。 这是我写的代码。

/* Binary Search Tree to Doubly Linked List conversion*/

static Node root2;

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

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

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

     // Recursively convert left subtree
    BinaryTree2DoubleLinkedList(root2.left);

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

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

 /* Function to print nodes in a given doubly linked list */
 void printList(Node node)
 {
     while (node != null) 
     {
         System.out.print(node.data + " ");
         node = node.right;
     }
 }

然而,当我填充我的BST时,只要我输入两个值,它就会给我一个StackOverlow Exception。 任何人都可以看看这个吗?

0 个答案:

没有答案