#include <iostream>
#include <vector>
#include <stack>
using namespace std;
//tree
class TreeNode{
public:
TreeNode(int data){
value = data;
left = NULL;
right = NULL;
}
public:
int value;
TreeNode* left;
TreeNode* right;
};
/*
class Solution{
public: int sum(int i, int k){
return i+k;
}
};*/
void print(TreeNode* head){
cout << head->value << " ";
}
//第一个是先序,第二个是中序,第三个是后序
void readorder(TreeNode* head){
if (head == NULL)
return;
//print(head);
readorder(head->left);
//print(head);
readorder(head->right);
print(head);
}
///***********************************************/unrecur
void preOrderUnrecur(TreeNode* head){
if (head != NULL){
stack<TreeNode*> s;
s.push(head);
while (!s.empty()){
head = s.top();
s.pop();
print(head);
if (head->right != NULL){
s.push(head->right);
}
if (head->left != NULL){
s.push(head->left);
}
}
}
cout << endl;
return;
}
//当前节点先把左边界压进去,找到最左边
//当前节点为空,从站拿一个打印,往右跑
//当前节点不为空,当前节点压入,往左跑
void inOrderUnrecur(TreeNode* head)
{
if (head != NULL){
stack<TreeNode*> s;
while (!s.empty() || head != NULL){
if (head != NULL){
s.push(head);
head = head->left;
}
else{
head = s.top();
s.pop();
print(head);
head = head->right;
}
}
}
return;
}
//先中右左,将打印的信息压入s2,然后出站左右中
void posOrderUnrecur(TreeNode* head){
if (head != NULL){
stack<TreeNode*> s1;
stack<TreeNode*> 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()){
print(s2.top());
s2.pop();
}
}
return;
}
//arr creat tree
void creatTree(TreeNode** head, int arr[], int len, int index = 0){
if (index > len - 1)
return;
(*head) = new TreeNode(arr[index]);
creatTree(&((*head)->left), arr, len, 2 * index + 1);
creatTree(&((*head)->right), arr, len, 2 * index + 2);
}
int main(){
int arr[] = {1,2,3,4,5};
TreeNode* head = NULL;
creatTree(&head, arr, 5);
readorder(head);
//preOrderUnrecur(head);
//inOrderUnrecur(head);
posOrderUnrecur(head);
//system();
return 0;
}
二叉树的遍历(递归&非递归)
最新推荐文章于 2024-04-08 22:10:05 发布