0

我被递归搜索困住了,我正在使用 gwt,基本上我想在 gwt 树中搜索一个节点,这是我的代码。提前谢谢。我不擅长递归:-(

public TreeItem search2(String sName, TreeItem node){
    TreeItem treeItem=null;
    String sValue ="";
    boolean bFound=false;

    System.out.println("Father Node:" + node.getText() + " child nodes:" + node.getChildCount());


    for (int i=0;i<node.getChildCount();i++){

        treeItem = node.getChild(i);
        sValue = treeItem.getText();
        System.out.println("searching...."+sValue);
        if (sValue.equalsIgnoreCase(sName)){
            bFound=true;
            System.out.println("!!found!!!!"+sName + " node to return:" + treeItem.getText());
            return treeItem;
        }
        else {
            return search2(sName,treeItem);
        }
    }               

    return treeItem;

}
4

1 回答 1

1

I think the error is in the line return search2(sName,treeItem);. Only if a match was found should you return ... if no match was found then you want to continue checking the rest of the child nodes. Try this:

public TreeItem search2(String sName, TreeItem node) {
    if (node.getText().equalsIgnoreCase(sName) {
        return node;
    }
    for (int i = 0; i < node.getChildCount(); i++) {
        TreeItem treeItem = search2(sName, node.getChild(i));
        if (treeItem != null) {
            return treeItem;
        }
    }
    return null;
}

Note: I edited my first answer because it would not have worked correctly if there was just one node (and the node text matched sName).

Andy

于 2013-02-06T20:54:58.787 回答