Shigure_Q 2016-11-07 16:17 采纳率: 50%
浏览 1090
已结题

二叉树递归遍历查找问题

如题,利用递归在二叉树中查找一个值,若二叉树中存在该值则输出1,否则输出0.我想用遍历进行查找,但是却无法进行,代码如下:
#include
#include
#include
#include
using namespace std;

class Tree_Node {
public:
char data; //数据
Tree_Node *left;
Tree_Node *right;

Tree_Node(char da) {
    left = right = NULL;
    data = da;
}

};
//删除二叉树 内联函数 减少时间花销
inline void free_Tree(Tree_Node *p) {
if(p -> left != NULL) {
free_Tree(p -> left);
}
if(p -> right != NULL){
free_Tree(p -> right);
}
delete(p);
}

void post_order(Tree_Node *p) {
if(p) {
post_order(p -> left);
post_order(p -> right);
cout << p -> data;
}
}

bool search(Tree_Node *p, char k) {
if(p -> data == k) {
return true;
}
if(p) {
search(p -> left, k);
search(p -> right, k);
}
}

void build_Tree(Tree_Node &p, string a) {
char ch;
int index = 0;
stack <Tree_Node
> s;
// stack s2;
ch = a[index++];
while(ch != '\0'){
p = new Tree_Node(ch);
if(s.size() > 0) {
p -> left = s.top();
s.pop();
}
s.push(p);
ch = a[index++];
if(ch == '\0') {
break;
}
if(ch != '\0' && s.top() -> left == NULL) {
p = s.top();
s.pop();
p -> left = new Tree_Node(ch);
ch = a[index++];
s.push(p);
}
if(ch == '\0') {
break;
}
if(ch != '\0') {
p = s.top();
s.pop();
p -> right = new Tree_Node(ch);
s.push(p);
ch = a[index++];
s.push(p);
}
if(ch == '\0') {
break;
}
}
p = s.top();
s.pop();
}

int main() {
string s;
char c;
Tree_Node *tree;
cin >> s >> c;
build_Tree(tree, s);
post_order(tree);
cout << endl;
if(search(tree, c)) {
cout << 1 << endl;
}
else {
cout << 0 << endl;
}
cout << 1 << endl;
free_Tree(tree);
return 0;
}
还有一个问题是不知道失败的判定条件,请大神帮帮忙修改一下代码

  • 写回答

4条回答 默认 最新

  • 一窝小猪仔 2016-11-08 01:10
    关注

    写代码注释多一点让人一眼能看懂。

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog