点击查看代码
//Binary tree traversal-- beadth-first and depth-first
#include<iostream>
#include<queue>//STL
using namespace std;
struct node {
int data;
node *left, *right;
};
node* getnewnode(int x)
{
node* temp = new node;
temp->data = x;
temp->left = temp->right = NULL;
return temp;
}
void insert(node*& travptr, int data) {//Node*& travptr 表示 travptr 是一个引用,引用的是一个指向 Node 类型的指针
if (travptr == NULL)
{
travptr = getnewnode(data);
return;
}
(data > travptr->data) ? insert(travptr->right, data) : insert(travptr->left, data);
}
//先根遍历
void preorder(node* root) {
if (root == NULL) return;//既是特殊情况,又是中止情况
cout << root->data << " ";
preorder(root->left);
preorder(root->right);
}//空间复杂度:O(h)where h is the height of the tree
//中根遍历
void inorder(node* root) {
if (root == NULL) return;
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}//空间复杂度:O(h)where h is the height of the tree
//后根遍历
void postorder(node* root) {
if (root == NULL) return;
postorder(root->left);
postorder(root->right);
cout << root->data << " ";
}//空间复杂度:O(h)where h is the height of the tree
int main()
{
node* root = NULL;
insert(root, 2);
insert(root, 1);
insert(root, 3);
insert(root, 0);
insert(root, 5);
preorder(root); cout << endl;
inorder(root); cout << endl;
postorder(root); cout << endl;
return 0;
}