前序遍历(递归版)
void BinTree::p_dfs(treeNode* u, int& inf, int* path) const{
if(u == NULL) return;
if(inf == total) return;
path[inf ++] = u->data;
p_dfs(u->left, inf, path);
p_dfs(u->right, inf, path);
}
int* BinTree::p_recursion() const{
if(root == NULL) return NULL;
int* path = new int[total];
int inf = 0;
p_dfs(root, inf, path);
for (int i = 0; i < total; i ++) printf("%d ", path[i]);
puts("");
return path;
}
前序遍历(非递归版)
int* BinTree::my_pre_traversal() const{
if(root == NULL) return NULL;
treeNode* now = root;
stack<treeNode*> st;
int* path = new int[total];
int inf = 0;
while(true)
{
while(now)
{
path[inf ++] = now->data;
st.push(now);
now = now->left;
}
if(st.size())
{
treeNode* u = st.top();
st.pop();
now = u->right;
}
else break;
}
for (int i = 0; i < total; i ++)
printf("%d ", path[i]);
puts("");
return path;
}
中序遍历(递归版)
void BinTree::m_dfs(treeNode* u, int& inf, int* path) const{
if(u == NULL) return;
if(inf == total) return;
m_dfs(u->left, inf, path);
path[inf ++] = u->data;
m_dfs(u->right, inf, path);
}
int* BinTree::m_recursion() const{
if(root == NULL) return NULL;
int* path = new int[total];
int inf = 0;
m_dfs(root, inf, path);
for (int i = 0; i < total; i ++) printf("%d ", path[i]);
puts("");
return path;
}
中序遍历(非递归版)
int* BinTree::my_mid_traversal() const{
if(root == NULL) return NULL;
stack<treeNode*> st;
treeNode* now = root;
int* path = new int[total];
int inf = 0;
while(true)
{
while(now)
{
st.push(now);
now = now->left;
}
if(st.size())
{
treeNode* u = st.top();
st.pop();
path[inf ++] = u->data;
now = u->right;
}
else break;
}
for (int i = 0; i < total; i ++)
printf("%d ", path[i]);
puts("");
return path;
}
后序遍历(递归版)
int* BinTree::po_recursion() const{
if(root == NULL) return NULL;
int* path = new int[total];
int inf = 0;
po_dfs(root, inf, path);
for (int i = 0; i < total; i ++)
printf("%d ", path[i]);
puts("");
return path;
}
void BinTree::po_dfs(treeNode* u, int& inf, int* path) const{
if(u == NULL) return;
if(inf == total) return;
po_dfs(u->left, inf, path);
po_dfs(u->right, inf, path);
path[inf ++] = u->data;
}
后序遍历(非递归版)
int* BinTree::post_traversal() const{
if(root == NULL) return NULL;
treeNode* now = root;
stack<treeNode*> st;
int* path = new int[total];
int inf = 0;
treeNode* last = NULL;
while(true)
{
while(now)
{
st.push(now);
now = now->left;
}
if(st.size())
{
treeNode* u = st.top();
st.pop();
if((!u->right) || last == u->right)
path[inf ++] = u->data, last = u;
else{
st.push(u);
now = u->right;
}
}
else break;
}
for (int i = 0; i < total; i ++) printf("%d ", path[i]);
puts("");
return path;
}
层次遍历
int* BinTree::floor_traversal() const{
if(root == NULL) return NULL;
queue<treeNode*> que;
int* path = new int[total];
int inf = 0;
que.push(root);
while(que.size())
{
treeNode* u = que.front();
que.pop();
path[inf ++] = u->data;
if(u->left) que.push(u->left);
if(u->right) que.push(u->right);
}
for (int i = 0; i < total; i ++) printf("%d ", path[i]);
puts("");
return path;
}