2013-07-02 74 views
0
public static BiNode linklist(BiNode root) 
{ 
    BiNode head = null, tail=null; 
    convertBST(head, tail, root); 
    return head; 
} 



public static void convertBST(BiNode head, BiNode tail, BiNode root) 
{ 
    BiNode leftTail = null, rightHead = null; 
    if(root==null){ 
     head = null; 
     tail = null; 
     return; 
    } 
    System.out.println("root = "+root.key); 
    convertBST(head, leftTail, root.node1); 
    convertBST(rightHead, tail, root.node2); 
    if(leftTail != null) 
    { 
     System.out.println("leftTail = "+leftTail.key); 
     leftTail.node2 = root; 
     root.node1 = leftTail; 
    }else{ 
     head = root; 
     System.out.println("head = "+ head.key+", root = "+root.key); 
    } 

     if(rightHead != null) 
     { 
     rightHead.node1 = root; 
     root.node2 = rightHead; 
     }else{ 
     tail = root; 
     System.out.println("tail = "+ tail.key+", root = "+root.key); 
     } 
    } 

上面是我的java代码,它用于将BST转换为双链表。将二叉搜索树转换为JAVA中的链接列表

但我不知道为什么头总是改变,这应该指向链接列表的头部,而不是改变。

我很高兴,伟大的头脑会帮助我调试此代码!谢谢!!!

+0

你能发布'linklist()'和'convertBST()'的代码吗?其他代码似乎都不会影响您的BST到链接列表逻辑,因此它只是将所有内容混淆在一起。 如果一切都整齐地缩进,它也会有所帮助。 –

回答

1

的基本关键,为什么代码是错的是这行:head = root;tail = root;的方法public static void convertBST(BiNode head, BiNode tail, BiNode root)

我们假定你是,当你将参数设置为一个新的节点将被传播调用堆栈(请参考)。 Java不会这样做。当您执行head = root;时,您只更改了本地值head而不是调用方法中的值。

因此在方法public static BiNode linklist(BiNode root){head永远是null和方法将总是返回null

+0

我明白了。但如何解决它?我知道如何解决在c/c + +中的这种问题,但如何解决它在JAVA?再次感谢你 – city

+0

返回值或传递值的可变包装 –