| 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
62
63
64
65
66
 | #define Element char
typedef struct Node{
  Element data;
  struct Node *left;
  struct Node *right;
}*Tree;
int i = 0;
//按照先序遍历建树
void construct_tree(Tree &root, Element data[]){
  Element e = data[i++];
  if(e == '#')
      root = NULL;
  else{
      root = new Node();
      root -> data = e;
      construct_tree(root -> left, data); //递归建立左子树
      construct_tree(root -> right, data); //递归建立右子树
  }   
}
void bfs(Tree root){  
  queue<Node *> q;
  q.push(root);
  while(!q.empty()){
      Node *temp = q.front();
      q.pop();
      cout<<temp -> data;
      if(temp -> left)
          q.push(temp -> left);
      if(temp -> right)
          q.push(temp -> right);
  }
}
void dfs(Tree root){
  stack<Node *> s;
  s.push(root);
  while(!s.empty()){
      Node *temp = s.top();
      s.pop();
      cout<<temp -> data;
      //因为stack是先进后出,所以先把right压进去
      if(temp -> right)
          s.push(temp -> right);
      if(temp -> left)
          s.push(temp -> left);
  }
}
int main(){
  //#表示没有左子树或者右子树
  //             A
  //           /   \
  //          B     C
  //        /  \   /  \
  //      D    E   F   G
  Element data[15] = {'A','B','D','#','#','E','#','#','C','F','#','#','G','#','#'};
  Tree tree;
  construct_tree(tree, data);
  //bfs
  cout<<"result of bfs: ";
  bfs(tree);
  cout<<endl;
  //dfs
  cout<<"result of dfs: ";
  dfs(tree);
  cout<<endl;
  return 0;
}
 |