簡體   English   中英

如果在樹中找不到輸入,如何使此遞歸二叉樹遍歷返回null?

[英]How can I make this recursive Binary Tree Traversal return null if the input is not found in the tree?

如果樹中不存在char,我不確定如何使此遞歸方法返回null

BinaryTreeNode<CharData> answer; // Declare answer variable to use in findChar method

public BinaryTreeNode<CharData> findChar(char ch, BinaryTreeNode<CharData> root){

// Base Case
if (root.getValue().getChar() == ch){
        answer =  root; // If the node "root" contains the character, then answer becomes root node. 
    }
    // Otherwise finish pre-order traversal
else {

    // Check that left child is not null. If not, recursive call for left child.
    if(root.getLeft() != null){
        findChar(ch, root.getLeft());
    }

    // Check that right child is not null. If not, recursive call for right child. 
    if(root.getRight() != null)
        findChar(ch, root.getRight());
    }
    return answer;
}

據我所知,必須在方法之外聲明answer ,以便任何東西都能返回。

但是,問題是,當我使用a for循環搜索列表字符時,在BinaryTree中不存在某些字符時,這些不存在的字符返回的answer的值就是其中的前一個字符的answer的值二叉樹中存在的列表。 我希望此方法為此類值返回null

幾點觀察1.出於多種原因,一個全局聲明的answer是一個問題。 2.您還缺少另一種情況:即rootnull 3. findChar返回一個值,您可以使用它。 4.您沒有利用您擁有搜索樹並且始終遍歷整個樹這一事實。 我在這里假設它確實是搜索樹,否則使用樹是沒有意義的。

所以我建議像這樣:

public BinaryTreeNode<CharData> findChar(char ch, BinaryTreeNode<CharData> root){
    if (root == null) {
        return null;
    }
    if (root.getValue().getChar() == ch){
        return root;
    }
    if (root.getValue().getChar() > ch) {
        return findChar(ch, root.getLeft());
    } else {
        return findChar(ch, root.getRight());
    }
}

如果它不是二叉搜索樹,則可以執行以下操作:

public BinaryTreeNode<CharData> findChar(char ch, BinaryTreeNode<CharData> root){
    if (root == null) {
        return null;
    }
    if (root.getValue().getChar() == ch){
        return root;
    }
    BinaryTreeNode<CharData> answer = findChar(ch, root.getLeft());
    if (answer != null) {
        return answer;
    } else {
        return findChar(ch, root.getRight());
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM