遍历算法
(the first node as the root node)
1.先(根)序遍历的递归算法定义:
若二叉树非空,则依次执行如下操作:
⑴ 访问根结点;
⑵ 遍历左子树;
⑶ 遍历右子树。
2.中(根)序遍历的递归算法定义:
若二叉树非空,则依次执行如下操作:
⑴遍历左子树;
⑵访问根结点;
⑶遍历右子树。
3.后(根)序遍历得递归算法定义:
若二叉树非空,则依次执行如下操作:
⑴遍历左子树;
⑵遍历右子树;
⑶访问根结点。
#include<iostream>
using namespace std;
struct Node {
Node *left;
Node *right;
int value;
explicit Node(int t) {
left = right = NULL;
value = t;
}
};
inline void insert_tree(Node *root, int v);
inline void print_inorder(Node *root);
inline void print_preorder(Node *root);
inline void print_postorder(Node *root);
inline void recycle_tree(Node *root);
int main() {
int n, temp;
cin >> n;
Node *root = NULL;
cin >> temp;
root = new Node(temp);
n--;
while (n--) {
cin >> temp;
insert_tree(root, temp);
}
cout << "Inorder:";
print_inorder(root);
cout << "\nPreorder:";
print_preorder(root);
cout << "\nPostorder:";
print_postorder(root);
cout << endl;
recycle_tree(root);
}
inline void insert_tree(Node *root, int v) {
if (v <= root->value) {
if (root->left == NULL) root->left = new Node(v);
else insert_tree(root->left, v);
} else {
if (root->right == NULL) root->right = new Node(v);
else insert_tree(root->right, v);
}
}
inline void print_inorder(Node *root) {
if (root == NULL) return;
print_inorder(root->left);
cout << " " << root->value;
print_inorder(root->right);
}
inline void print_preorder(Node *root) {
if (root == NULL) return;
cout << " " << root->value;
print_preorder(root->left);
print_preorder(root->right);
}
inline void print_postorder(Node *root) {
if (root == NULL) return;
print_postorder(root->left);
print_postorder(root->right);
cout << " " << root->value;
}
inline void recycle_tree(Node *root) {
if (root == NULL) return;
recycle_tree(root->left);
recycle_tree(root->right);
delete root;
}