简体   繁体   English

如何在二叉树中搜索一个节点并返回它?

[英]How to search for a node in a binary tree and return it?

I'm trying to search for a node in a binary tree and return in case it's there, otherwise, return null. By the way, the node class has a method name() that return a string with it's name...What I have so far is:我正在尝试在二叉树中搜索一个节点并返回以防它存在,否则返回 null。顺便说一句,节点 class 有一个方法 name() 返回一个带有它的名字的字符串......我到目前为止是:

private Node search(String name, Node node){

     if(node != null){
         if(node.name().equals(name)){
            return node;
         }

      else{
         search(name, node.left);
         search(name, node.right);
      }
    }
    return null;
}

Is this correct??这样对吗??

You need to make sure your recursive calls to search return if the result isn't null.如果结果不为空,您需要确保对搜索的递归调用返回。

Something like this should work...像这样的东西应该工作......

private Node search(String name, Node node){
    if(node != null){
        if(node.name().equals(name)){
           return node;
        } else {
            Node foundNode = search(name, node.left);
            if(foundNode == null) {
                foundNode = search(name, node.right);
            }
            return foundNode;
         }
    } else {
        return null;
    }
}
public Node findNode(Node root, Node nodeToFind) {
    Node foundNode = null;
    Node traversingNode = root;

    if (traversingNode.data == nodeToFind.data) {
        foundNode = traversingNode;
        return foundNode;
    }

    if (nodeToFind.data < traversingNode.data
            && null != traversingNode.leftChild) {
        findNode(traversingNode.leftChild, nodeToFind);
    } else if (nodeToFind.data > traversingNode.data
            && null != traversingNode.rightChild) {
        findNode(traversingNode, nodeToFind);
    }

    return foundNode;

}

Since language doesn't matter much for this question, here's what it looks in C# with pre-order traversal:由于语言对这个问题没有太大影响,下面是它在 C# 中使用预序遍历的样子:

public static Node FindNode(Node n, int nodeValue)
{
    if (n == null) return null;
    if (n.Value == nodeValue) return n;
    return FindNode(n.Left, nodeValue) ?? FindNode(n.Right, nodeValue);
}
Boolean FindInBinaryTreeWithRecursion(TreeNode root, int data)
{
    Boolean temp;
    // base case == emptytree
    if (root == null) return false;
    else {
        if (data == root.getData())  return true;
        else { // otherwise recur down tree
            temp = FindInBinaryTreeWithRecursion(root.getLeft(), data);
            if (temp != true) 
                return temp;
            else
                return (FindInBinaryTreeWithRecursion(root.getRight(), data));  
        }
    }
}
public static TreeNode findNodeInTree(TreeNode root, TreeNode nodeToFind) {
  if (root == null) {
    return null;
  }

  if (root.data == nodeToFind.data) {
    return root;
  }

  TreeNode found = null;
  if (root.left != null) {
    found = findNodeInTree(root.left, nodeToFind);
    if (found != null) {
      return found;
    }
  }

  if (root.right != null) {
    found = findNodeInTree(root.right, nodeToFind);
    if (found != null) {
      return found;
    }
  }
  return null;
}

Actually, try to avoid recursivity.实际上,尽量避免递归。 In case you have big tree structure you will get stack overflow error.如果你有大树结构,你会得到堆栈溢出错误。 Instead of this you can use a list:你可以使用一个列表来代替这个:

private Node search(String name, Node node){
    List<Node> l = new ArrayList<Node>();
    l.add(node);
    While(!l.isEmpty()){
        if (l.get(0).name().equals(name))   
            return l.get(0);
        else {
            l.add(l.get(0).left);
            l.add(l.get(0).right);
            l.remove(0);
        }           
    }   
    return null;
}
public static boolean findElement(Node root, int value) {
    if (root != null) {
        if (root.data == value) {
            return true;
        } else {
            return findElement(root.left, value) || findElement(root.right, value);
        }
    }
    return false;
}
    public TreeNode searchBST(TreeNode root, int val) {
        if(root==null || root.val==val) return root;
        TreeNode found = (val < root.val) ? searchBST(root.left,val) : searchBST(root.right,val);
        return found;
    }

View Code on GitHub 在 GitHub 上查看代码

This might be better:这可能会更好:

if(node != null){
    if(node.name().equals(name)){
        return node;
    }
    else {
        Node tmp = search(name, node.left);
        if (tmp != null) { // if we find it at left
            return tmp; // we return it
        }
        // else we return the result of the search in the right node
        return search(name, node.right);
    }
}
return null;

you should return something if it is found in node.left or node.right so the else block should be something like that:如果在 node.left 或 node.right 中找到它,你应该返回一些东西,所以 else 块应该是这样的:

 else{
     Node temp = search(name, node.left);
     if (temp != null) return temp;
     temp = search(name, node.right);
     if (temp != null) return temp;
  }

you don't do anything with the result of the recursive calls你不会对递归调用的结果做任何事情

Node res = search(name, node.left);
if(res!=null)return res;
res = search(name, node.right);
if(res!=null)return res;
private TreeNode findX(TreeNode root, int x) {
    if(root == null) return null;
    if(root.val == x) return root;

    TreeNode left = findX(root.left,x);
    TreeNode right = findX(root.right,x);

    if(left == null) return right;
    return left;

}
Node* search(Node* root,int key){
   
   // If key is found or is NULL     
   if (root == NULL || root->key == key) 
      return root;

   if (root->key < key) 
      return search(root->right, key); 
   
   return search(root->left, key);
} 

For C++ guys:对于 C++ 人:

//search in a binary tree | O(n)
TreeNode* searchBST(TreeNode* root, int val) {
    if(!root) return root;
    if(root->val == val) return root;

    TreeNode* temp = searchBST(root->left, val);
    if(!temp){
        temp = searchBST(root->right, val);
    }
    return temp;
}

//search in a BST | O(logn)
TreeNode* searchBST(TreeNode* root, int val) {
    if(!root) return root;
    if(root->val == val) return root;
    if(val < root->val) return searchBST(root->left, val);
    return searchBST(root->right, val);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM