二叉树遍历(大部分)失败

Binary Tree Traversal (Mostly) Failing

对于class,我必须创建一个状态对象的二叉树,每个状态对象都包含一个常驻对象的二叉树,组织居住在每个状态的人。我正在尝试按名称在整个州树中搜索一个人(州树和居民树都是按名称的字母顺序排列的),这涉及遍历整个州树并在每个州的居民树中搜索该人。显然我的状态树遍历不起作用,因为大多数时候,当我知道一个事实时,它告诉我这个人不在数据库中(即我的 stateforperson 方法,如下所列,树 returns NULL)它们确实存在于数据库中。我确定我的 searchfor() 方法有效。

node <Person*> * stateforperson (string nm, node <T> * n)
{    if (n !=  NULL)
     {
         node <Person*> * person = n->data->residents->searchfor(nm);
         if (person != NULL)
             return person;
         return stateforperson(nm, n->left);
         return stateforperson(nm, n->right);
     }
     else
         return NULL;
}

尝试更新:

node <Person*> * stateforperson (string nm, node <T> * n)
{        if (n !=  NULL)
         {
             node <Person*> * person = n->data->residents->searchfor(nm);
             if (person != NULL)
                 return person;
             // Here, you explore the left branch and get the results.
             node <Person*> * left_ret = stateforperson(nm, n->left);
             // Here, same with right branch.
             node <Person*> * right_ret = stateforperson(nm, n->right);
             // You now have both results.
             if (left_ret != NULL) // If a result was found in left branches, you return that person. 
                 return left_ret;
             else if (right_ret != NULL) // Same with right branch.
                 return right_ret;
             else // The problem was here. Before you returned uninitialized memory. (because there wasn't a specified return value.
             // Now, you return a NULL pointer if nothing was found. 
             //So you detect that no person was found and don't use unitialized memeory.
                 return (NULL);
              }
              else
                  return NULL;
    }

我相信发生的事情是你只探索了左边的节点。永远不要向右走,因为你 return 之前 :

     return stateforperson(nm, n->left); 
     // Here you just return the left part. Never reaching the following line
     return stateforperson(nm, n->right);

尝试实际存储值和更多类似的东西:

    left_ret = stateforperson(nm, n->left);
    right_ret = stateforperson(nm, n->right);

然后根据需要对变量进行任何检查以 return 正确。

(我相信这至少是问题所在。有一段时间没有进行任何递归编程,所以我可能会弄错。)