先序遍历:根→左→右
中序遍历:左→根→右
后序遍历:左→右→根
#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
void preorder(Node* node)//先序遍历
{
if (node != NULL)
{
cout << node->data <<endl;
preorder(node->left);
preorder(node->right);
}
}
void inorder(Node* node)//中序遍历
{
if (node != NULL)
{
inorder(node->left);
cout << node->data << endl;
inorder(node->right);
}
}
void postorder(Node* node)//后序遍历
{
if (node != NULL)
{
postorder(node->left);
postorder(node->right);
cout << node->data << endl;
}
}
int main()
{
Node n1, n2, n3, n4;
n1.data = 5;
n2.data = 6;
n3.data = 7;
n4.data = 8;
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n2.right = NULL;
n3.left = NULL;
n3.right = NULL;
n4.left = NULL;
n4.right = NULL;
//preoder(&n1);
//inorder(&n1);
postorder(&n1);
}
一般不用上面这样
#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
struct Tree
{
Node* root;
};
void insert(Tree* tree, int value)
{
Node* node= new Node;
node->data = value;
node->left = NULL;
node->right = NULL;
if (tree->root == NULL)
{
tree->root = node;
}
else
{
Node* temp = tree->root;
while (temp != NULL)
{
if (value < temp->data)
{
if (temp->left == NULL)
{
temp->left = node;
return;
}
else
{
temp = temp->left;
}
}
else
{
if (temp->right == NULL)
{
temp->right = node;
return;
}
else
{
temp = temp->right;
}
}
}
}
}
int get_height(Node* node)//求高度
{
if (node == NULL)
{
return 0;
}
else
{
int left_h = get_height(node->left);
int right_h = get_height(node->right);
int max = left_h;
if (right_h > max)
{
max = right_h;
}
return max + 1;
}
}
int get_max(Node* node)
{
if (node == NULL)
{
return -1;
}
else
{
int m1 = get_max(node->left);
int m2 = get_max(node->right);
int m3 = node->data;
int max = m1;
if (m2 > max) { max = m2; }
if (m3 > max) { max = m3; }
return max;
}
}
void preorder(Node* node)//先序遍历
{
if (node != NULL)
{
cout << node->data <<endl;
preorder(node->left);
preorder(node->right);
}
}
void inorder(Node* node)//中序遍历
{
if (node != NULL)
{
inorder(node->left);
cout << node->data << endl;
inorder(node->right);
}
}
void postorder(Node* node)//后序遍历
{
if (node != NULL)
{
postorder(node->left);
postorder(node->right);
cout << node->data << endl;
}
}
int main()
{
int arr[7] = { 6,4,7,3,8,9,5 };
Tree tree;
tree.root = NULL;
for (int i = 0;i < 7;i++)
{
insert(&tree, arr[i]);
}
cout << "显示" << endl;
preorder(tree.root);
//inorder();
//postorder();
int h = get_height(tree.root);
cout << "高度为" << h << endl;
int m = get_max(tree.root);
cout << "最大值为" << m << endl;
}