2013-07-07 520 views
4

當我將節點添加到二叉樹並試圖顯示有關它的信息時,不顯示信息。我認爲我在遞歸插入算法中引用了一些問題,但無法修復它。遞歸二叉樹插入

package test; 

class BinaryTree<T> { 
    private static class Node<T> { 
     int key; 
     T data; 
     Node<T> leftChild; 
     Node<T> rightChild; 

     public Node(int key,T data) { 
      this.key = key; 
      this.data = data; 
     } 
    } 

    public Node<T> rootNode; 

    public BinaryTree() { 
     rootNode = null; 
    } 

    public Node<T> getRootNode() { 
     return rootNode; 
    } 

    // insert node into binary tree 
    public void insertNode(int key,T data, Node<T> rootNode) { 
     // to create new node 

     // if tree doesn't have root elements 
     if(rootNode == null) { 
      rootNode = new Node<T>(key,data); 
      rootNode.leftChild = null; 
      rootNode.rightChild = null; 
     } 
     else { 
      Node<T> focusNode = rootNode; 

      if(key >= focusNode.key) { 
       insertNode(key,data,focusNode.rightChild); 
      } 
      else { 
       insertNode(key,data,focusNode.leftChild); 
      } 
     } 
    } 

    // inorder traverse tree 
    public void inOrderTraverseTree(Node<T> focusNode) { 
     if(focusNode != null) { 
      inOrderTraverseTree(focusNode.leftChild); 
      System.out.println(focusNode.data); 
      inOrderTraverseTree(focusNode.rightChild); 
     } 
    } 
} 

public class MyApp { 
    public static void main(String[] args) { 
     BinaryTree<String> bintree = new BinaryTree<String>(); 
     bintree.insertNode(3, "Boss", bintree.rootNode); 
     bintree.inOrderTraverseTree(bintree.rootNode); 
    } 
} 

如果我用這個算法添加節點並嘗試顯示信息,它就可以工作。我如何解決遞歸算法的問題?

public void addNode(int key, T name) { 
     Node<T> newNode = new Node<T>(key,name); 
     if(rootNode == null) { 
      rootNode = newNode; 
     } 
     else { 
      Node<T> focusNode = rootNode; 
      Node<T> parent; 
      while(true) { 
       parent = focusNode; 
       if(key < focusNode.key) { 
        focusNode = focusNode.leftChild; 
        if(focusNode == null) { 
         parent.leftChild = newNode; 
         return; 
        } 
       } 
       else { 
        focusNode = focusNode.rightChild; 
        if(focusNode == null) { 
         parent.rightChild = newNode; 
         return; 
        } 
       } 
      } 
     } 
    } 

感謝您的幫助。

回答

3

您的代碼快速一瞥 - 我發現在這部分,你要檢查空,根節點變量是函數的局部。因此,您所創建的新節點逃脫立即退出函數拋出後,它不會改變你的成員字段

// if tree doesn't have root elements 
    if(rootNode == null) { 
     rootNode = new Node<T>(key,data); 
     rootNode.leftChild = null; 
     rootNode.rightChild = null; 
    } 

您需要使用this.rootNode = new Node<T>(key,data);替代,或者用不同的局部變量的名稱,以避免混淆

+0

+1爲偉大的bug視覺。提問:多麼糟糕的名字選擇! –

+0

@gerrytan感謝您的幫助。) – veinhorn