二叉树的结构
class Node<V>{
V value;
Node left;
Node right;
}
二叉树的遍历
分别是前序、中序、后续、层序遍历。
//递归实现的前序遍历
static void preOrderRecur(Node* head){
if(head == NULL)
return;
cout << head->data << " ";
preOrderRecur(head->left);
preOrderRecur(head->right);
}
//递归实现的中序遍历
static void inOrderRecur(Node* head){
if(head == NULL)
return;
inOrderRecur(head->left);
cout << head->data << " ";
inOrderRecur(head->right);
}
//递归实现的后序遍历
static void posOrderRecur(Node*head){
if(head == NULL)
return;
posOrderRecur(head->left);
posOrderRecur(head->right);
cout << head->data << " ";
}
//非递归实现的前序遍历
static void preOrderUnRecur(Node* head){
if(head == NULL)
return;
stack<Node*> s;
s.push(head);
while(!s.empty()){
head = s.top();
cout << head->data << " ";
s.pop();
if(head->right != NULL)
s.push(head->right);
if(head->left != NULL)
s.push(head->left);
}
}
//非递归实现的中序遍历
static void inOrderUnRecur(Node* head){
if(head == NULL)
return;
stack<Node*> s;
while(!s.empty()|| head != NULL){
if(head != NULL){
s.push(head);
head = head->left;
}else{
head = s.top();
cout << head->data << " ";
s.pop();
head = head->right;
}
}
}
//非递归实现的后序遍历
static void posOrderUnRecur_1(Node* head){
if(head == NULL){
return;
}
stack<Node*> s1;
stack<Node*> s2;
s1.push(head);
while(!s1.empty()){
head = s1.top();
s1.pop();
s2.push(head);
if(head->left != NULL){
s1.push(head->left);
}
if(head->right != NULL){
s1.push(head->right);
}
}
while(!s2.empty()){
cout << s2.top()->data << " ";
s2.pop();
}
}
//宽度优先遍历
static void breadthFirstTravel(Node* head){
if(head == NULL){
return;
}
queue<Node*> q;
q.push(head);
while(!q.empty()){
head = q.front();
cout << head->data << " ";
q.pop();
if(head->left != NULL){
q.push(head->