2016-04-03 38 views
0

我会提到,这是作业。我非常困惑我需要做些什么才能使add()函数正常工作。令人困惑的是,我们需要将左右子项定义为BinaryTree类型,并且add()函数采用String而不是Node,我在本网站的每个示例中都会看到这一点。我想不出如何设置一个字符串到一个新的孩子,这是一个BinaryTree类型。Java - 非常困惑这个递归二叉树

任何帮助&指导表示赞赏。

import java.util.*; 

public class BinaryTree { 
    private String data; 
    private BinaryTree leftChild; 
    private BinaryTree rightChild; 


    public BinaryTree() { 
    data = null; 
    leftChild = null; 
    rightChild = null; 
    } 


    public BinaryTree(String d) { 
    data = d; 
    leftChild = null; 
    rightChild = null; 
    } 

    public BinaryTree(String d, BinaryTree left, BinaryTree right) { 
    data = d; 
    leftChild = left; 
    rightChild = right; 
    } 


    public String getData() { return data; } 
    public BinaryTree getLeftChild() { return leftChild; } 
    public BinaryTree getRightChild() { return rightChild; } 


    public void setData(String d) { data = d; } 
    public void setLeftChild(BinaryTree left) { leftChild = left; } 
    public void setRightChild(BinaryTree right) { rightChild = right; } 


    public String root; 

    //This function is what I'm stuggling with 
    public void add(String item){ 



    if(root==null) 
    { 
     root = item; 
    } 
    else 
    { 
     String tmp = root; // save the current root 
     if(root.compareTo(item)>0) 
     { 
      setData(item); 
      add(item); //I should have setBinaryTree(item) here, but I can't convert type String to BinaryTree?. 
     } 
     else if(root.compareTo(item)<0) 
     { 
      setData(item); 
      add(item); 
     } 
     root = tmp; // put the root back to its original value 
    } 
    return; 
    } 
    } 

回答

0

您需要在遍历树时递归。您目前正在尝试添加在同一个节点上。做这样的事情。

if(root.compareTo(item)>0) 
{ 
    if (leftChild == null) { 
     leftChild = new BinaryTree(item); 
    } else { 
     leftChild.add(item); 
    } 
} 

并为正确的孩子做类似的事情。

0

您需要做的是使用提供的构造函数创建一个新的BinaryTree对象,并将其分配给左侧或右侧的子项。

public void add(String item){ 



    if(root==null){ 
     root = item; 
    }else{ 
     String tmp = root; // save the current root 
     BinaryTree bTree = new BinaryTree() 
     if(root.compareTo(item)>0){ 
      bTree.setData(item); 
      setLeftChild(bTree); 
     }else if(root.compareTo(item)<0){ 
      bTree.setData(item); 
      setRightChild(bTree); 
     } 
     root = tmp; // put the root back to its original value 
    } 
    return; 
}