如何在二叉树中查找节点并返回?

发布于 2024-11-05 19:14:58 字数 396 浏览 1 评论 0原文

我试图在二叉树中搜索一个节点,如果存在则返回,否则返回 null。顺便说一句,节点类有一个方法 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;
}

这是正确的吗?

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:

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??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

浊酒尽余欢 2024-11-12 19:14:58

如果结果不为空,您需要确保对搜索的递归调用返回。

像这样的东西应该有效......

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;
    }
}

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;
    }
}
空袭的梦i 2024-11-12 19:14:58
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;

}
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;

}
葬花如无物 2024-11-12 19:14:58

由于语言对于这个问题来说并不重要,因此 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);
}

Since language doesn't matter much for this question, here's what it looks in C# with pre-order traversal:

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);
}
晨敛清荷 2024-11-12 19:14:58

如果在 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 should return something if it is found in node.left or node.right
so the else block should be something like that:

 else{
     Node temp = search(name, node.left);
     if (temp != null) return temp;
     temp = search(name, node.right);
     if (temp != null) return temp;
  }
因为看清所以看轻 2024-11-12 19:14:58

您不对递归调用的结果执行任何操作

Node res = search(name, node.left);
if(res!=null)return res;
res = search(name, node.right);
if(res!=null)return res;

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;
帅哥哥的热头脑 2024-11-12 19:14:58

这可能会更好:

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;

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;
枕梦 2024-11-12 19:14:58
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));  
        }
    }
}
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));  
        }
    }
}
牵你手 2024-11-12 19:14:58
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;
}
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;
}
晨敛清荷 2024-11-12 19:14:58

实际上,尽量避免递归。
如果你有大的树结构,你会得到堆栈溢出错误。
您可以使用列表代替:

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;
}

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;
}
客…行舟 2024-11-12 19:14:58
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 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;
}
寄风 2024-11-12 19:14:58
    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;
    }

在 GitHub 上查看代码

    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

蝶…霜飞 2024-11-12 19:14:58
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;

}
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;

}
莫相离 2024-11-12 19:14:58
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);
} 
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);
} 
孤君无依 2024-11-12 19:14:58

对于 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);
}

For C++ guys:

//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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文