在二叉树中查找值为x的结点,试编写算法(用c语言)打印值为x的节点的所有祖先,假设值为x的结点不多于1个
#include <iostream>
#include <stack>
#include<queue>
typedef struct treenode{
char data;
struct treenode *left;
struct treenode *right;
}treenode,*ptreenode;
ptreenode buytreenode(char x)
{
ptreenode n=(ptreenode) malloc(sizeof (treenode));
n->data=x;
n->left= nullptr,n->right= nullptr;
return n;
}
ptreenode build_tree()
{
ptreenode root= buytreenode('A');
root->left= buytreenode('B');
root->right= buytreenode('C');
root->left->left= buytreenode('D');
root->left->right= buytreenode('E');
root->right->left= buytreenode('F');
root->right->right= buytreenode('G');
root->left->left->left= buytreenode('H');
root->left->left->right= buytreenode('I');
return root;
}
void print_tree(ptreenode root) {
std::queue<ptreenode> tmp;
tmp.push(root);
int s = tmp.size();
while (!tmp.empty()) {
ptreenode t = tmp.front();
tmp.pop();
s--;
printf("%3c", t->data);
if (t->left) tmp.push(t->left);
if (t->right) tmp.push(t->right);
if (s == 0) puts(""), s = tmp.size();
}
}
void path(ptreenode root,char x)
{
ptreenode pre= nullptr,pointer=root;
std::stack<ptreenode> tmp;
while(pointer||!tmp.empty())
{
while(pointer) tmp.push(pointer),pointer=pointer->left;
pointer=tmp.top();
if(pointer->data==x){
while(!tmp.empty()){
printf("%3c",tmp.top()->data);
tmp.pop();
}
return;
}
if(pointer->left&&pointer->right!=pre){
pointer=pointer->right;
}else{
tmp.pop();
pre=pointer;
pointer= nullptr;
}
}
}
int main() {
ptreenode root=build_tree();
print_tree(root);
puts("");
path(root,'H');
puts("");
path(root,'I');
puts("");
path(root,'B');
puts("");
path(root,'F');
puts("");
path(root,'G');
return 0;
}