cout didn't work properly in my Binary tree

Hi all,
I was trying to parse a string to a binary tree but I can't figure out what's wrong with my code, basically, I want to parse the string "(hu)" and put h and u on the two branches, first, in the main part, the two cout give me strange characters. but if I comment any one of the cout sentence, it just worked fine. second, the post order travasal function post failed me. if any of you can give me some idea about what had happened, I'll be greatly appreciated. thank you very much!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <string>
#include <fstream>
using std::cout;
using std::endl;
using namespace std;
using  std::string;

class tree{
public:
	tree(); 
	char node;
	tree *left;
	tree *right;
};

tree::tree(){node='N',left=NULL,right=NULL;}

tree parse(char *&p){
	tree t;
	if(*p=='('){
		t.node='N';
		p++;
		
		tree t_l=parse(p);
		t.left=&t_l;
		p++;
		
		tree t_r=parse(p);
		t.right=&t_r;
	}
	else{
		t.node = *p;
		t.left=NULL;
		t.right=NULL;
	}
	return t;
}

void post(tree t){
	if(t.left != NULL){
		post(*(t.left));
	}
	if(t.right != NULL){
		post(*(t.right));
	}
          if(&t != NULL){
	        cout << t.node << endl;
	}

}

int main(){
	char str[] = "(hu)";
	char *p=&str[0];
	tree t = parse(p);
	cout << t.node << endl;
	cout << t.left->node << endl;
	post(t);
	return 0;
}
Last edited on
Let's see...
Line 55: &str[0]==str
Line 19: The function is returning a copy of a tree. Return a pointer to a tree and save the copy constructor a pointless call.
Lines 25 and 29: More copies of trees. Instead of a function, make parse a constructor of tree with this prototype: tree(char **); (you'll need to change the pointer to the C string). Then you can change these two lines to something like this->right=new tree(p);. That look a lot nicer, now, doesn't it?

Ah, here's the problem. On lines 25 and 29 you're making non-local pointers point to local data. Once the function returns, these pointers become invalid. You can fix this by changing your design.
Topic archived. No new replies allowed.