Data Structure Binary Tree: Print ancestors of a given binary tree node without recursion
2024-10-02 07:25:24
http://www.geeksforgeeks.org/print-ancestors-of-a-given-binary-tree-node-without-recursion/
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <string>
#include <fstream>
#include <map>
using namespace std; struct node {
int data;
struct node *left, *right;
node() : data(), left(NULL), right(NULL) { }
node(int d) : data(d), left(NULL), right(NULL) { }
}; void printancestor(node *root, int key) {
if (!root) return;
stack<node*> S;
while () {
while (root && root->data != key) {
S.push(root);
root = root->left;
}
if (root && root->data == key) break;
if (S.top()->right == NULL) {
root = S.top();
S.pop();
while (!S.empty() && S.top()->right == root) {
root = S.top();
S.pop();
}
}
root = S.empty()? NULL : S.top()->right;
}
while (!S.empty()) {
cout << S.top()->data << " ";
S.pop();
}
} int main() {
node *root = new node();
root->left = new node();
root->right = new node();
root->left->left = new node();
root->left->right = new node();
root->right->left = new node();
root->right->right = new node();
root->left->left->left = new node();
root->left->right->right = new node();
root->right->right->left = new node();
for (int i = ; i < ; i++) {
printancestor(root, i);
cout << endl;
}
return ;
}
最新文章
- NodeJS写个爬虫,把文章放到kindle中阅读
- 安卓开发:一种快速提取安卓app的UI图标资源的方法
- C#随学随记
- okhttp-utils的封装之okhttp的使用
- Php output buffering缓存及程序缓存
- vector容器总结.xml
- 【Android开发】完美解决Android完全退出程序
- Linux中环境变量到底写在哪个文件中?解析login shell 和 no-login shell
- AutoPy首页、文档和下载 - 跨平台的Python GUI工具包 - 开源中国社区
- Android 服务类Service 的具体学习
- Proxy SwitchySharp chrome网络代理【转】
- CTF中常见密码题解密网站总结
- [BZOJ]2458: [BeiJing2011]最小三角形
- NiftyNet 数据预处理
- nmap扫描测试
- 关于全局变量,static,define和const
- 聊聊找AI算法岗工作
- bash中的pasue
- Python的set集合
- str相关操作
热门文章
- Convolutional Patch Networks with Spatial Prior for Road Detection and Urban Scene Understanding
- php里面用魔术方法和匿名函数闭包函数动态的给类里面添加方法
- thread.join() 方法存在的必要性是什么?
- python 的三元表达式
- php7.0 出现 curl_setopt(): Disabling safe uploads is no longer supported in 报错!
- Python 类方法、实例方法、静态方法
- COM线程单元
- Linq系列(7)——表达式树之ExpressionVisitor
- vagrant系列四:vagrant搭建redis与redis的监控程序redis-stat
- 安卓常用的xml控件配件的使用包含shape,declare-styleable、selector