不按顺序搜索二进制搜索树

时间:2017-03-08 00:28:11

标签: java binary-search-tree

我有一个由值x排序的对象的二叉搜索树(具有较低值x的对象被添加到左侧,而较大值的对象被添加到右侧)。

他们还有一个属性y,这是一个非常无序的属性。我如何搜索树中的每个节点以找到匹配?如果没有匹配,我将如何返回null?

我目前的代码(确实有很多缺陷因此我要问的原因)是:

public BinaryTreeNode<E> inOrderIdSearch(BinaryTreeNode<E> n, int usrId) {
      if (n!=null) {
          inOrderIdSearch(n.getLeft(),usrId);
          if (n.getValue().getId() == usrId) {
            return n;
          }
          inOrderIdSearch(n.getRight(),usrId);
      }
      return null;
  }

2 个答案:

答案 0 :(得分:0)

public BinaryTreeNode<E> inOrderIdSearch(BinaryTreeNode<E> n, int usrId) {
  if(n==null) return null;
  int candidate=n.getValue().getId();
  if(candidate==userId) return n;

  return inOrderIdSearch(candidate>userId?n.getLeft():n.getRight(),userId);
}

答案 1 :(得分:0)

假设您的树没有根据您要搜索的值进行排序,您必须搜索每个节点,并且遍历的顺序无关紧要。因此,在去孩子之前先搜索每个节点。您还需要返回递归调用的结果,而不是像上面那样忽略它们。

public BinaryTreeNode<E> inOrderIdSearch(BinaryTreeNode<E> n, int usrId) {
    if (n==null) {
        return null;
    }
    if (n.getValue().getId() == usrId) {
        return n;
    }
    BinaryTreeNode<E> leftResult =inOrderIdSearch(n.getLeft(),usrId);    
    if (leftResult!=null) {
        return leftResult;
    }
    BinaryTreeNode<E> rightResult = inOrderIdSearch(n.getRight(),usrId);
    if (rightResult != null) {
        return rightResult;
    }
}