有没有一种好的递归算法来在树中查找值?

问题描述

我有一个树型数据结构,我想在其中确定一个节点中是否存在值。

该树不是二叉树;每个节点可以有无限数量的子节点。

我想做一个递归算法,以便一旦找到该值,就返回一个真值。而且,如果访问每个节点都没有找到该值,则返回一个错误值。

事实证明,这比我想象的要难一些。我可以访问每个节点-但是我不确定何时返回错误值。

这是我的伪代码

boolean doesValueExist(tree,value) {

    for (int ii=0; ii<tree.numChildren; ii++) {
        if (tree.getChild(ii).value = value) {
            return true;
        }
        return doesValueExist(tree.getChildren());
    }

    //When do a return a false value?
}

谢谢

解决方法

我会做类似的事情(基本上是在树上遍历图):

 boolean doesValueExist(tree,value) {
      // value found in the current node
      if(tree.value == value) {
             return true;
      }

      for (int ii=0; ii<tree.numChildren; ii++) {
             //the value found in one of the subtrees
             if (doesValueExist(tree.getChild(ii),value) {
                 return true;
             }
       }

       //the value was not found in any subtree
       return false;
  }
,

谢谢-非常感谢。

我正试图给你功劳。由于某种原因,没有显示接受图标。