打印祖先递归函数逻辑

时间:2019-11-14 19:46:42

标签: c++ algorithm tree binary-search-tree

我需要实现这个递归的void函数,该函数将打印给定元素(x)的祖先,还有其他方法,但是我很好奇我的逻辑有什么问题吗?

例如,如果我们要查找C的祖先,它将打印B A,因为 C是B的孩子,B是A的孩子

逻辑:我们一直遍历直到找到元素X,然后我们击中了基本情况,因此我们利用堆栈来打印基本上将成为父元素的堆栈元素

这是我的代码,假设我们有指向父级的指针,并且提供了BST的所有内容:

void ancestor (BinaryNode * root, int x)
{

   //no need to check null assume x exist in the  BST
   if(root->data==x)
      return;
   if(root->data>x)
   {
      ancestor(root->left,x)
   }
   else
   {
      ancestor(root->right,x)

   }
   cout<<root->data<<endl;
}

0 个答案:

没有答案