首页 > 解决方案 > 打印祖先递归函数逻辑

问题描述

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

例如,如果我们想找到 C 的祖先:它将打印 BA,因为 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;
}

标签: c++algorithmtreebinary-search-tree

解决方案


推荐阅读