struct TreeNode {
char data;
TreeNode* lchild;
TreeNode* rchild;
};
void medMethodDG(TreeNode* root) {
if (root == NULL) {
return;
}
medMethodDG(root->lchild);
cout << " " << root->data << " ";
medMethodDG(root->rchild);
}
TreeNode* copyTree(TreeNode* node) {
if (node == NULL) {
return NULL;
}
TreeNode* nnode = NULL;
TreeNode* lnode = NULL;
TreeNode* rnode = NULL;
if (node->lchild != NULL) {
lnode = copyTree(node->lchild);
}
if (node->rchild != NULL) {
rnode = copyTree(node->rchild);
}
nnode = new TreeNode;
nnode->data = node->data;
nnode->lchild = lnode;
nnode->rchild = rnode;
}
//非递归中序遍历
/*步骤一:
1.节点有左子树,入栈
2.节点没有左子树,访问该节点
步骤二:
1.如果节点有右子树,重复步骤一
2.如果节点没有右子树,访问结束,根据栈顶回退,访问右子树,重复步骤一
若栈为空,遍历结束
*/
TreeNode* findLNode(TreeNode* node, stack<TreeNode*>& s) {
if (node == NULL) {
return NULL;
}
TreeNode* nnode = node;
while (nnode->lchild != NULL) {
s.push(nnode);
nnode = nnode->lchild;
}
return nnode;
}
void medMethod(TreeNode* node) {
stack<TreeNode*> s;
TreeNode* nnode = node;
nnode = findLNode(node, s);
while (nnode) {
cout << nnode->data<<" ";
if (nnode->rchild != NULL) {//节点有右子树,找左子树
nnode = findLNode(nnode->rchild,s);
}
else if (!s.empty() && nnode->rchild == NULL) {//节点没有右子树,栈顶回退
nnode = s.top();
s.pop();
}
else {
nnode = NULL;
}
}
}
/*
非递归先序遍历
*/
void preMethod(TreeNode* node) {
deque<TreeNode*> d;
if (node == NULL) return;
d.push_front(node);
while (!d.empty())
{
TreeNode* current = d.front();
d.pop_front();
if (current->rchild != NULL) d.push_front(current->rchild);
if (current->lchild != NULL) d.push_front(current->lchild);
cout << current->data << ' ';
}
cout << endl;
}
/*
非递归后序遍历
*/
void postMethod(TreeNode* node) {
if (node == NULL) {
return;
}
stack<char> sta;
deque<TreeNode*> deq;
deq.push_front(node);
while (!deq.empty()) {
TreeNode* current = deq.front();
deq.pop_front();
sta.push(current->data);
if (current->lchild != NULL) {
deq.push_front(current->lchild);
}
if (current->rchild != NULL) {
deq.push_front(current->rchild);
}
}
while (!sta.empty()) {
cout << sta.top() << " ";
sta.pop();
}
}
int main() {
TreeNode t1, t2, t3, t4, t5;
memset(&t1, 0, sizeof(t1));
memset(&t2, 0, sizeof(t2));
memset(&t3, 0, sizeof(t3));
memset(&t4, 0, sizeof(t4));
memset(&t5, 0, sizeof(t5));
t1.data = 'A';
t2.data = 'B';
t3.data = 'C';
t4.data = 'D';
t5.data = 'E';
t1.lchild = &t2;
t1.rchild = &t3;
t2.lchild = &t4;
t3.lchild = &t5;
//cout << "递归中序遍历: ";
//medMethodDG(&t1);
//cout << endl;
//cout << "非递归中序遍历:";
//medMethod(&t1);
//cout << endl;
//preMethod(&t1);
postMethod(&t1);
system("pause");
return 0;
}
树的拷贝及非递归遍历
于 2022-09-05 20:20:43 首次发布