二叉樹非遞歸 先序,中序
1
#include<iostream>
2
#include<stack>
3
using namespace std;
4
5
struct BinTreeNode{
6
int data;
7
BinTreeNode *left;
8
BinTreeNode *right;
9
};
10
void preOrder1(BinTreeNode *root){//先序1
11
stack<BinTreeNode*> s;
12
BinTreeNode *tmp=root;
13
while(tmp!=NULL || !s.empty()){
14
while(tmp!=NULL){
15
cout<<tmp->data<<' ';
16
s.push(tmp);
17
tmp = tmp->left;
18
}
19
if(!s.empty()){
20
tmp = s.top()->right;
21
s.pop();
22
}
23
}
24
}
25
void preOrder2(BinTreeNode *root){//先序2
26
stack<BinTreeNode*> s;
27
BinTreeNode *tmp=root;
28
while(tmp!=NULL || !s.empty()){
29
while(tmp!=NULL){
30
cout<<tmp->data<<' ';
31
s.push(tmp->right);
32
tmp = tmp->left;
33
}
34
if(!s.empty()){
35
tmp = s.top();
36
s.pop();
37
}
38
}
39
}
40
void InOrder(BinTreeNode *root){//中序
41
stack<BinTreeNode*> s;
42
BinTreeNode *tmp=root;
43
while(tmp!=NULL || !s.empty()){
44
while(tmp!=NULL){
45
s.push(tmp);
46
tmp = tmp->left;
47
}
48
if(!s.empty()){
49
cout<<s.top()->data<<' ';
50
tmp = s.top()->right;
51
s.pop();
52
}
53
}
54
}

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

posted on 2011-08-18 15:14 Hsssssss 閱讀(117) 評論(0) 編輯 收藏 引用 所屬分類: C++代碼