c++ - 打印祖先递归函数逻辑
问题描述
我需要实现这个将打印给定元素 (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;
}
解决方案
推荐阅读
- mysql - 如何查询数据库中的所有表
- typo3 - TYPO3 Extbase TCA MM 关系过滤器结果由站点定义的常量“newRecordStoragePid”
- java - 从 sqlite 获取的数据未显示在 recyclerview 中
- ios - 计算可见 CGRect 以裁剪 UIImageView
- c# - Onesignal c# web_buttons
- postgresql - 如何创建这个数据库?
- rabbitmq - RabbitMQ crashes when entering UI
- http - Cannot make a successful curl put call in PHP
- java - JShell 的限制是什么?
- ssl - AWS 上的 Kubernetes:使用 nginx-ingress + cert-manager 保留客户端 IP