1. 程式人生 > >二叉樹的 前序 || 中序 || 後序遍歷

二叉樹的 前序 || 中序 || 後序遍歷

中序遍歷 == ren c++ 代碼 right 結點 esp style

直奔代碼:

  1 ///前序遍歷:先遍歷根節點,再遍歷左子樹,最後遍歷右子樹
  2 /*
  3 #include <bits/stdc++.h>
  4 using namespace std;
  5 
  6 struct tree
  7 {
  8     struct tree *left;
  9     int date;
 10     struct tree *right;
 11 };
 12 typedef struct tree treenode;
 13 typedef struct tree * b_tree;
 14 
 15 b_tree add(b_tree root, int node)    ///插入結點+
16 { 17 b_tree newnode; 18 b_tree currentnode; 19 b_tree parentnode; 20 21 newnode = (b_tree)malloc(sizeof(treenode)); 22 newnode->date = node; 23 newnode->left = NULL; 24 newnode->right = NULL; 25 26 if(root == NULL) ///第一個結點建立 27 return newnode;
28 else 29 { 30 currentnode = root; ///儲存當前結點 31 while(currentnode != NULL) ///當前結點不為空 32 { 33 parentnode = currentnode; ///儲存父結點 34 if(currentnode->date > node) 35 currentnode = currentnode->left; ///左子樹 36 else
37 currentnode = currentnode->right; ///右子樹 38 } 39 if(parentnode->date > node) 40 parentnode->left = newnode; 41 else 42 parentnode->right = newnode; 43 } 44 return root; 45 } 46 47 b_tree create(int *data, int len) 48 { 49 int i; 50 b_tree root = NULL; 51 for(int i = 1; i <= len; i++) 52 { 53 root = add(root, data[i]); 54 } 55 return root; 56 } 57 58 void print(b_tree root) 59 { 60 if(root != NULL) 61 { 62 cout << root->date << ‘ ‘; 63 print(root->left); 64 print(root->right); 65 } 66 } 67 68 int main() 69 { 70 int N; 71 b_tree root = NULL; 72 cin >> N; 73 int node[N+1]; 74 for(int i = 1; i <= N; i++) 75 cin >> node[i]; 76 root = create(node, N); 77 print(root); 78 cout << endl; 79 return 0; 80 } 81 */ 82 83 84 ///中序遍歷:先遍歷左子樹,再遍歷根結點,最後才遍歷右子樹 85 /* 86 void print(b_tree root) 87 { 88 if(root != NULL) 89 { 90 print(root->left); 91 cout << root->date << ‘ ‘; 92 print(root->right); 93 } 94 } 95 */ 96 97 ///後序遍歷:先遍歷左子樹,再遍歷右子樹,最後才遍歷根結點 98 /* 99 void print(b_tree root) 100 { 101 if(root != NULL) 102 { 103 print(root->left); 104 print(rooy->right); 105 cout << root->date << ‘ ‘; 106 } 107 } 108 */

二叉樹的 前序 || 中序 || 後序遍歷